递归读取带有文件夹的目录

Posted

技术标签:

【中文标题】递归读取带有文件夹的目录【英文标题】:Recursively read a directories with a folder 【发布时间】:2018-03-05 13:39:06 【问题描述】:

我一直在尝试使用 fs 模块请求递归读取目录。一路上我遇到了问题,它只给了我一个文件名。这就是我需要的样子:

文件名。 还有那个文件的目录。 此结果可以作为对象或散装到数组中。

请大家帮忙。 谢谢。

【问题讨论】:

"还有那个文件的目录" 你已经有了这个,否则使用的 fs 方法不会知道你试图读取哪个目录。如果您指的是每个子目录的路径,那么随着您的深入,只需将每个子目录名称连接到路径即可。但是如果没有看到您的代码,我们无法具体告诉您如何修复您的代码。 【参考方案1】:

这是一个递归解决方案。您可以对其进行测试,将其保存在文件中,然后运行 ​​node yourfile.js /the/path/to/traverse

const fs = require('fs');
const path = require('path');
const util = require('util');

const traverse = function(dir, result = []) 
    
    // list files in directory and loop through
    fs.readdirSync(dir).forEach((file) => 
        
        // builds full path of file
        const fPath = path.resolve(dir, file);
        
        // prepare stats obj
        const fileStats =  file, path: fPath ;

        // is the file a directory ? 
        // if yes, traverse it also, if no just add it to the result
        if (fs.statSync(fPath).isDirectory()) 
            fileStats.type = 'dir';
            fileStats.files = [];
            result.push(fileStats);
            return traverse(fPath, fileStats.files)
        

        fileStats.type = 'file';
        result.push(fileStats);
    );
    return result;
;

console.log(util.inspect(traverse(process.argv[2]), false, null));

输出如下所示:

[
  
    file: 'index.js',
    path: '/***/test-class/index.js',
    type: 'file'
  ,
  
    file: 'message.js',
    path: '/***/test-class/message.js',
    type: 'file'
  ,
  
    file: 'somefolder',
    path: '/***/test-class/somefolder',
    type: 'dir',
    files: [
      file: 'somefile.js',
      path: '/***/test-class/somefolder/somefile.js',
      type: 'file'
    ]
  ,
  
    file: 'test',
    path: '/***/test-class/test',
    type: 'file'
  ,
  
    file: 'test.c',
    path: '/***/test-class/test.c',
    type: 'file'
  
]

【讨论】:

以上是关于递归读取带有文件夹的目录的主要内容,如果未能解决你的问题,请参考以下文章

103)PHP,递归读取目录内容

使用 Cordova 递归读取所有文件和文件夹结构

Linux Shell之递归读取指定目录下的所有文件

递归读取制定目录下所有文件夹和文件的实现(java)

如何在Go中递归列出带有频道的文件?

Java读取指定目录下的所有文件(子目录里的文件也可递归得到)