递归读取带有文件夹的目录
Recursively read a directories with a folder
我一直在尝试使用 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: '/Whosebug/test-class/index.js',
type: 'file'
},
{
file: 'message.js',
path: '/Whosebug/test-class/message.js',
type: 'file'
},
{
file: 'somefolder',
path: '/Whosebug/test-class/somefolder',
type: 'dir',
files: [{
file: 'somefile.js',
path: '/Whosebug/test-class/somefolder/somefile.js',
type: 'file'
}]
},
{
file: 'test',
path: '/Whosebug/test-class/test',
type: 'file'
},
{
file: 'test.c',
path: '/Whosebug/test-class/test.c',
type: 'file'
}
]
我一直在尝试使用 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: '/Whosebug/test-class/index.js',
type: 'file'
},
{
file: 'message.js',
path: '/Whosebug/test-class/message.js',
type: 'file'
},
{
file: 'somefolder',
path: '/Whosebug/test-class/somefolder',
type: 'dir',
files: [{
file: 'somefile.js',
path: '/Whosebug/test-class/somefolder/somefile.js',
type: 'file'
}]
},
{
file: 'test',
path: '/Whosebug/test-class/test',
type: 'file'
},
{
file: 'test.c',
path: '/Whosebug/test-class/test.c',
type: 'file'
}
]