递归读取目录与文件夹
问题描述:
我一直在试图申请一个递归读取目录与FS模块。我一路上都遇到过问题,它只给我一个文件名。以下是我需要它的方式:递归读取目录与文件夹
- 文件名。
- 还有该文件的目录。 这个结果可能是作为一个对象或被放入一个数组中。
请人帮忙。 谢谢。
答
这里是一个递归解决方案。您可以测试它,将它保存在一个文件中,运行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' } ]
+0
它的工作原理!非常感谢。你是最棒的 –
请告诉我们你有什么到目前为止已经试过 –
_“并且还该文件的目录” _你已经有了这个,否则使用FS方法止跌不知道你想读的是哪个目录。如果您是指每个子目录的路径,那么只要将每个子目录名称连接到路径就可以了。但是如果没有看到您的代码,我们无法具体告诉您如何修复您的代码。 –