简体   繁体   English

如何正确地递归遍历磁盘目录,并使用node.js以相对格式将所有路径流式传输到json中?

[英]How to properly walk a disk directory recursively and stream all the paths in relative format into a json using node.js?

I'm trying to read directory tree and save it into a JSON file using node.js with the following logic: 我正在尝试使用node.js通过以下逻辑读取目录树并将其保存到JSON文件中:

  1. Read specified directory 读取指定目录
  2. Transform (or get in the first place if possible?) the paths into relative format. 将路径转换(或如果可能的话放在第一位?)转换为relative格式。 Something like this: 像这样:

Directory: C:/test 目录: C:/test

{
{"C:/test folder 1": [
  {"folder 1": ["file1.txt", "file2.txt"]}, 
  "file1.txt",
  "file2.txt",
  ...
]},
{"C:/test folder 2": [
  {"folder 1": ["file1.txt", "file2.txt"]}, 
  "file1.txt",
  "file2.txt",
  ...
]},
"file1.txt",
"file2.txt",
"file3.txt",
...
}
  1. Stream that object into a JSON file (I need to stream it because the object is quite big) 将对象流式传输到JSON文件中(由于对象很大,因此我需要对其进行流式传输)

I was trying to use different npm modules like: 我试图使用不同的npm模块,例如:

walkdir , walker , node-klaw + fs-extra.writeJson , json-object-stream , etc. walkdirwalkernode-klaw + fs-extra.writeJsonjson-object-stream

But I keep getting different errors trying to stream it into a json. 但是,尝试将其流式传输到json时,我一直遇到不同的错误。

Following script should work for you, just replace __dirname with absolute path of location that you want to list. 以下脚本应该对您有用,只需将__dirname替换为要列出的绝对位置路径即可。 And update filename where to write it 并更新文件名写在哪里

I am not checking here if first time call actually gets valid folder, and there might be thing with / regarding on OS 我不是在这里检查第一次调用是否实际上获得了有效的文件夹,并且在OS上可能存在与/有关的问题

removeNamespace flag here is only so that first level keeps absolute path and not in following removeNamespace标志在这里只是为了使第一级保持绝对路径,而不是紧随其后

var fs = require("fs");

function getContentForLocation(location, removeNamespace) {
    let result = [];
    let content = fs.readdirSync(location);
    content.forEach(c => {
        if(fs.statSync(`${location}/${c}`).isFile()) result.push(c);
        else {
            let name = removeNamespace ? c : `${location}/${c}`;
            result.push({
                [`${name}`]: getContentForLocation(`${location}/${c}`, true)
            })
        }
    });
    return result;
}
let tree = JSON.stringify(getContentForLocation(__dirname))
fs.writeFileSync(`${__dirname}/test.json`, tree)

Async version: 异步版本:

var fs = require("fs");

function getContentForLocation(location, callback, removeNamespace) {
    let result = [];

    let folderNames = [];
    fs.readdir(location, (err, content) => {
        content.forEach(c => {
            if(fs.statSync(`${location}/${c}`).isFile()) result.push(c);
            else folderNames.push(c);
        });
        if(folderNames.length === 0) callback(result)
        else folderNames.forEach(folder => {
            let name = removeNamespace ? folder : `${location}/${folder}`;
            getContentForLocation(`${location}/${folder}`, resolveCallback.bind(this, name, folder),true)
        })
    });

    function resolveCallback(name, folder, content) {
        result.push({ [name]: content });
        folderNames = folderNames.filter(f => f !== folder);
        if(folderNames.length === 0) callback(result);
    }
}

getContentForLocation(__dirname, results => {
    console.log("resolved", results)
    fs.writeFile(`${__dirname}/test.json`, JSON.stringify(results), (err) => { console.log(err) })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM