NodeJs利用fs模块,实现批量生成文件

传入三个参数,分别代表在当前目录中生成文件的数量,文件名称,以及文件后缀名

function generator(count,filename,suffix) {
  count = parseInt(count);
  const fs = require('fs');
  const path = require('path');
  const length = count.toString().length;
  const htmlDoc=
  `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

</body>
</html>`;
  const jsDoc=`'use stict';`;
  const content=suffix=='js'?jsDoc:htmlDoc;
  for (let i = 1; i < count + 1; i++) { let relativename=`${filename+i.toString() }.`+suffix; let fullname=path.join(__dirname, relativename); fs.stat(fullname,function(err,stat){ if(!(stat && stat.isFile())){ fs.writeFile(fullname,content); } }); } }

导出文件,默认文件后缀为html

exports.init = (args) => {
  const count = args[0];
  const filename=args[1] || 'index';
  const suffix=args[2] || 'html';
  if (count) {
    generator(count,filename,suffix);
  } else {
    const readline = require('readline');
    const rl = readline.createInterface(process.stdin, process.stdout);
    rl.question('生成几个代码文件?', (c) => { generator(c,filename,suffix); rl.close(); }); } };

输入node app init或者直接node app init 8即可看到效果

你可能感兴趣的:(NodeJs利用fs模块,实现批量生成文件)