Node.js/fs:修订间差异
来自康健生活
创建页面,内容为“== 标题文字 == == 写入 == == 批量生成文件 ==” |
|||
| 第2行: | 第2行: | ||
== 写入 == | == 写入 == | ||
== 批量生成文件 == | == 批量生成文件 == | ||
{{Hc|create.js|<syntaxhighlight lang="javascript"> | |||
const fs = require('fs'); | |||
const path = require('path'); | |||
function generator(count,filename,suffix) { | |||
count = parseInt(count); | |||
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 foo = `; | |||
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 + i, ()=>{console.log(i)}); | |||
} | |||
}); | |||
} | |||
} | |||
const 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(); | |||
}); | |||
} | |||
}; | |||
init([process.argv[2], process.argv[3], process.argv[4]]); | |||
</syntaxhighlight>}} | |||
生成文件。 | |||
{{shc|<syntaxhighlight lang="bash"> | |||
node create.js 200 testfile_ js</syntaxhighlight>|$|/home/kangkk}} | |||