fs 模块
主要是提供一些操做 磁盘文件 的 api,基本上构建工具 都要用到 fs
去对文件进行 读 和 写。javascript
fs 模块
咋一看文档,api贼多,简直没法直视。java
而后再看一下,发现其实能够一分为二,api大都分为同步的和异步的,这样分析就会以为好多了。node
因而乎,半抄半写的作了个 json 文件合并的小demo,功能就是读取指定目录下的 json 文件,而后写到同一个 json 文件里面去。shell
新建一个工做目录,进入到 工做目录后 npm init -y
, 而后在目录下新建一个名字为 json
的文件夹,放几个json文件进去。npm
再在工做目录新建一个 index.js
, 代码以下:json
const fs = require('fs');
const path = require('path');
const exists = filePath => fs.existsSync(filePath);
// 获取 命令行传入的 json 目录
const jsonPath = process.argv[2];
if (!jsonPath) {
console.log('未传入json目录');
process.exit(1);
}
const rootPath = path.join(process.cwd(), jsonPath);
const newFilePath = './data.json';
// 遍历目录下的 json 文件
function walkJsonFile(dirPath) {
const files = fs.readdirSync(dirPath);
const result = [];
files.forEach(file => {
const filePath = `${dirPath}/${file}`;
const stat = fs.statSync(filePath);
if ( stat.isFile() && (/\.json$/).test(file) ) {
result.push(filePath);
}
});
return result;
}
// 合并 json 文件内容 到 newJson 文件夹
function mergeJsonFile() {
const files = walkJsonFile(rootPath);
if (!files.length) process.exit(2);
const data = files
.filter(exists)
.reduce((total, file) => {
const fileData = fs.readFileSync(file);
// 获取文件名称
const baseName = path.basename(file, '.json');
let fileJson
try {
fileJson = JSON.parse(fileData);
} catch (err) {
console.log(err);
}
total[baseName] = fileJson;
// 若是不想区分 baseName, 直接合并便可
// total = { ...total, ...fileJson };
return total;
}, {});
fs.writeFileSync(newFilePath, JSON.stringify(data, null, 2));
}
mergeJsonFile();
复制代码
在工做目录下运行api
node index.js json
复制代码
就能够看到代码被合并到新文件中了。异步
效果如图:工具
参考ui