递归读取包含文件夹

时间:2017-09-24 13:48:02

标签: javascript html node.js fs

我一直试图请求以 fs 模块递归读取目录。我一路上遇到了问题,只给了我一个文件名。以下是我需要的方式:

  • 文件名。
  • 还有该文件的目录。 此结果可以作为对象或批量生成数组。

任何人都请帮忙。 感谢。

1 个答案:

答案 0 :(得分: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: '/stackoverflow/test-class/index.js',
    type: 'file' },
  { file: 'message.js',
    path: '/stackoverflow/test-class/message.js',
    type: 'file' },
  { file: 'somefolder',
    path: '/stackoverflow/test-class/somefolder',
    type: 'dir',
    files: 
     [ { file: 'somefile.js',
         path: '/stackoverflow/test-class/somefolder/somefile.js',
         type: 'file' } ] },
  { file: 'test',
    path: '/stackoverflow/test-class/test',
    type: 'file' },
  { file: 'test.c',
    path: '/stackoverflow/test-class/test.c',
    type: 'file' } ]
相关问题