创建时间:2019-10-15测试环境:win10node-v10.16.1受到vue-cli初始化项目的启发,想探究其原理,自己实现一套类似的方法,在项目中创建通用模板块。下面介绍node.js自带的readline的三种实现方式。使用流程实现第三方包查询器。还有commander.js等其他的实现方式,这里不详述所有实现方式的完整代码。github链接的链接文件结构如下|--generatorTemplate.js(生成模板)|--readline.js(readline模式下的完整代码)|--process.js(process模式下的完整代码)|--templateinquirer.js创建的例子(inquirer模式完整代码):根据用户输入不同的结果返回不同的结果,包括生成文件夹的实现,文件夹内容如下|--template|--css|--图像|--js|--索引。要求('readline');初始创建constrl=readline.createInterface({/*监听可读流*/input:process.stdin,/*读写可写流*/output:process.stdout,/*提示信息*///prompt:'请输入:'});这里会一直监听用户的输入,并在输入模板时创建一个模板rl.on('line',function(input){if(input==='template'){/*生成器方法见下文*/generatorTemplate.generator()rl.close()}elseif(input==='pause'){rl.pause()}else{rl.write('请正确输入:');}})完成readline.js更多使用参考代码见:官方文档readline使用process在用户输入为template时生成模板constprocessFn=()=>{consthandleInput=(input)=>{if(input==='student'){process.stdout.write('这里有学生:hew\n')}elseif(input==='template'){/*看这里的生成器方法*/generatorTemplate.generator()process.stdin.emit('结束');}else{process.stdout.write('一些其他输入消息\n')process.stdin.emit('end');}}process.stdin.setEncoding('utf-8')process.stdin.on('readable',()=>{letchunk=null;while((chunk=process.stdin.read())!==null){if(typeofchunk==='string'){chunk=chunk.slice(0,-2);if(chunk){handleInput(chunk)}else{process.stdin.emit('end');}}}})process.stdin.on('end',()=>{process.stdout.write('end\n');process.exit()})}完整代码更多使用参考参见process.js:官方文档process使用inquirerinquirer.prompt([{type:'confirm',name:'toBeDelivered',message:'Doyouwanttogenerateatemplate?',default:false},{type:'checkbox',name:'choices',message:'Isthisfordelivery?',default:'check',choices:['yes','no']}]).then(answers=>{console.log(answers);/*输出值:{toBeDelivered:true,choices:['name']}*/if(answers.toBeDelivered&&answers.choices[0]==='yes'){/*生成器方法见下文*/generatorTemplate.generator();}else{console.log('不生成模板');}});inquirer.js更多使用参考完整代码见:官方文档Generatetemplatemethodcalledbyinquirer(generatormethod)generator.jsconstfs=require('fs');constpath=require('路径');constjsStr=`consta='';constb=1;exportdefault{a:a,b:b}`functiongenerator(){fs.mkdirSync(path.join(__dirname,'template'));fs.mkdirSync(path.join(__dirname,'template','css'));fs.mkdirSync(path.join(__dirname,'template','js'));fs.mkdirSync(path.join(__dirname,'template','images'));fs.writeFileSync(path.join(__dirname,'template','js','index.js'),jsStr,'utf-8')}exports.generator=generator;欢迎交流Github
