首页 > 解决方案 > 如何从文件夹及其子文件夹中读取文件并写入 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。有没有人可以帮助我实现这一目标。谢谢。

标签: javascriptnode.jsgulp

解决方案


这样的事情应该可以正常工作:

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();

推荐阅读