index.js

import program from 'commander';
import inquirer from 'inquirer';
import downloadGit from 'download-git-repo';
import ora from 'ora';
import chalk from 'chalk';
import fs from 'fs/promises';
const projectList = [
    // { name: 'cd-web-m', value: 'http://git.daicms.com/cd-web-m.git#master' },
    { name: 'dai-vue-m', value: 'http://git.daicms.com/dai-vue-temp-m.git#master' },
    { name: 'dai-web-w', value: 'http://git.daicms.com/dai-vue-temp-m.git#master' }
];
program
    .command('init')
    // .alias('i')
    // .description('初始化')
    // .option('-x, --xxx', 'xxx') // 有参数时使用
    .action(async () => {
        let answers = await inquirer.prompt([
            {
                name: 'name',
                message: '请输入项目名称'
            },
            {
                name: 'description',
                message: '请输入项目描述(可为空)',
                default: 'description'
            },
            {
                name: 'author',
                message: '请输入作者名称(可为空)',
                default: 'description'
            },
            {
                type: 'list',
                name: 'url',
                message: '请选择项目类型',
                choices: projectList
            }
        ]);
        console.log(answers);
        let isExist = false;
        try {
            await fs.stat(answers.name);
            isExist = true;
            console.error(chalk.red('目录已经存在,创建失败'));
        } catch (ex) {}
        if (!isExist) {
            const spinner = ora('下载中...');
            spinner.start();
            downloadGit('direct:' + answers.url, answers.name, { clone: true }, async (err) => {
                if (err) {
                    spinner.fail();
                    console.log(chalk.red(err));
                } else {
                    spinner.succeed();
                    const fileName = `${answers.name}/package.json`;
                    const meta = {
                        name: answers.name,
                        description: answers.description,
                        author: answers.author
                    };
                    // if (await fs.access(fileName)) {
                    let content = await fs.readFile(fileName);
                    content = JSON.parse(content.toString());
                    Object.assign(content, meta);
                    await fs.writeFile(fileName, JSON.stringify(content, null, 4));
                    // }
                    console.log(chalk.green('项目创建成功'));
                }
            });
        }
    });

program.parse(process.argv);