javascript - 如何从文件夹及其子文件夹中读取文件并写入 JSON 文件?
问题描述
我想从一个文件夹及其子文件夹中读取文件名,并想创建mainfest.JSON
一个包含所有文件名列表的新文件。
这是要求
**Input:**
\Temp\file1.txt
\Temp\file2.log
\Temp\subTemp\file3.txt
\Temp\subTemp\file4.txt
**Output**
Mainefest.json
[
“file1.txt” : “\Temp\file1.txt”,
“file2.log” : “\Temp\file2.log”,
“file3.txt” : “\Temp\ subTemp \file1.txt”,
“file4.txt” : “\Temp\ subTemp \file1.txt”
]
下面是我的示例代码
gulp.task('TestApp', function(){
return gulp.src('./Temp/**/*.*')
.pipe(
hash({
algorithm: 'md5',
hashLength: 20
})) // Add hashes to the files' names
.pipe(gulp.dest('./Output')) // Write the renamed files
.pipe(hash.manifest('mainfest.json', {
deleteOld: true,
sourceDir: __dirname + './output'
})) // Switch to the manifest file
});
它运作良好。但它添加了我不想要的哈希值。
我被允许使用 javascript、gulp、node js。有没有人可以帮助我实现这一目标。谢谢。
解决方案
这样的事情应该可以正常工作:
const path=require('path'),
fs=require('fs');
class Parser{
constructor(dir,out){
this.dir=dir;
this.out=out;
}
parse(){
const res=[];
this._parse(this.dir,res);
fs.writeFileSync(this.out,JSON.stringify(res));
}
_parse(dir,result){
for(const entry of fs.readdirSync(dir)){
if(fs.lstatSync(path.join(dir,entry)).isDirectory()){
this._parse(path.join(dir,entry),result);
}else{
const e={};
e[entry]=path.join(dir,entry)
result.push(e)
}
}
}
}
module.exports=Parser;
你可以像这样使用它:
const parser=require('path/to/file/contains/class'),
Parser=new parser('dir/to/read','path/to/output/file.json');
Parser.parse();
推荐阅读
- sql-server - 如何真正撤消错误选择的索引创建?
- xamarin - Jenkins 无法从 dl.google.com / maven.google.com 下载 xamarin 依赖项
- azure - 如何在没有特定参数的情况下创建通用 docker 镜像
- spring-boot - WebSocket握手期间的Spring启动错误:意外的响应代码:403
- html - html和css中的div对齐
- r - 按日期排序的直方图
- excel - 循环遍历从 1 到 31 的列
- docker - GitLab Docker Runner 重用已安装的软件层
- c# - C# - 从客户端检查 TCP/IP 套接字状态
- node.js - 由于 MongoDB,Heroku 中的应用程序错误?