【问题标题】:Is there a way to see files inside directories by reading the parent dir using fs?有没有办法通过使用 fs 读取父目录来查看目录中的文件?
【发布时间】:2021-06-25 21:18:21
【问题描述】:

所以使用 fs,我想读取某个目录(我们称之为父目录)中的所有内容,包括其他目录、其他目录中的文件以及父目录中的文件。 例如: 父路径:

/Parent/

Parent 中的所有内容

/Parent/index.js
/Parent/utils/utils.js
/Parent/Structures/thing.js

我怎样才能得到这一切?我试过fs.readdirfs.readdirSync 但它只读取文件,而不是目录。

【问题讨论】:

    标签: node.js path fs


    【解决方案1】:

    好吧,如果您可以在您的环境中访问 Bash,则可以使用 exec() 执行 find

    例子:

    const { exec } = require("child_process");
    
    exec("find /Parent/", (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
    });
    

    cmets 后更新:

    使用递归函数递归获取目录下的所有文件:

    const fs = require("fs")
    const path = require("path")
    
    const getAllFiles = function(dirPath, arrayOfFiles) {
      files = fs.readdirSync(dirPath)
    
      arrayOfFiles = arrayOfFiles || []
    
      files.forEach(function(file) {
        if (fs.statSync(dirPath + "/" + file).isDirectory()) {
          arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles)
        } else {
          arrayOfFiles.push(path.join(__dirname, dirPath, "/", file))
        }
      })
    
      return arrayOfFiles
    }
    

    参考:https://coderrocketfuel.com/article/recursively-list-all-the-files-in-a-directory-using-node-js

    【讨论】:

    • 是的,但我想使用 fs。
    • 使用递归函数怎么样?本文中提到了一种方法:coderrocketfuel.com/article/…
    • @user14428154 更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2022-01-16
    • 1970-01-01
    • 2019-09-26
    相关资源
    最近更新 更多