Node.js/fs:修订间差异
来自康健生活
< Node.js
无编辑摘要 |
|||
| 第81行: | 第81行: | ||
{{shc|<syntaxhighlight lang="bash"> | {{shc|<syntaxhighlight lang="bash"> | ||
node create.js 200 testfile_ js</syntaxhighlight>|$|/home/kangkk}} | node create.js 200 testfile_ js</syntaxhighlight>|$|/home/kangkk}} | ||
== 扩展 == | |||
{| class="wikitable" | |||
|- | |||
| fs-extra || 示例 || 示例 | |||
|- | |||
| 示例 || 示例 || 示例 | |||
|- | |||
| 示例 || 示例 || 示例 | |||
|} | |||
2022年11月2日 (三) 04:02的版本
标题文字
existsSync
验证文件/文件夹是否存在。
fs.existsSync(_path);
mkdir
fs.mkdir('./path/to/dir', {recursive: true}, err => {});
// or
fs.promises.mkdir('./path/to/dir', {recursive: true});
node.js 引入 recursive。
mkdirSync
递归创建文件夹。
fs.mkdirSync('./path/to/dir', {recursive: true});
writeFileSync
const filePath = './path/to/dir/file';
const folderPath = path.dirname(filePath);
if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, {recursive: true});
fs.writeFileSync(filePath, _buffer);
批量生成文件
create.js
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]]);
生成文件。
/home/kangkk
node create.js 200 testfile_ js
扩展
| fs-extra | 示例 | 示例 |
| 示例 | 示例 | 示例 |
| 示例 | 示例 | 示例 |
No categories