I’ve been trying to request a recursively read a directory with fs module. I had problems along the way, its only giving me a file name. Here’s how I need it to be:
- File name.
- And also a directory of that file. This results may be as an object or bulked into an array.
Anyone please help. Thanks.
Advertisement
Answer
Here is a recursive solution. You can test it, save it in a file, run node yourfile.js /the/path/to/traverse
.
JavaScript
x
32
32
1
const fs = require('fs');
2
const path = require('path');
3
const util = require('util');
4
5
const traverse = function(dir, result = []) {
6
7
// list files in directory and loop through
8
fs.readdirSync(dir).forEach((file) => {
9
10
// builds full path of file
11
const fPath = path.resolve(dir, file);
12
13
// prepare stats obj
14
const fileStats = { file, path: fPath };
15
16
// is the file a directory ?
17
// if yes, traverse it also, if no just add it to the result
18
if (fs.statSync(fPath).isDirectory()) {
19
fileStats.type = 'dir';
20
fileStats.files = [];
21
result.push(fileStats);
22
return traverse(fPath, fileStats.files)
23
}
24
25
fileStats.type = 'file';
26
result.push(fileStats);
27
});
28
return result;
29
};
30
31
console.log(util.inspect(traverse(process.argv[2]), false, null));
32
Output looks like this :
JavaScript
1
33
33
1
[
2
{
3
file: 'index.js',
4
path: '/stackoverflow/test-class/index.js',
5
type: 'file'
6
},
7
{
8
file: 'message.js',
9
path: '/stackoverflow/test-class/message.js',
10
type: 'file'
11
},
12
{
13
file: 'somefolder',
14
path: '/stackoverflow/test-class/somefolder',
15
type: 'dir',
16
files: [{
17
file: 'somefile.js',
18
path: '/stackoverflow/test-class/somefolder/somefile.js',
19
type: 'file'
20
}]
21
},
22
{
23
file: 'test',
24
path: '/stackoverflow/test-class/test',
25
type: 'file'
26
},
27
{
28
file: 'test.c',
29
path: '/stackoverflow/test-class/test.c',
30
type: 'file'
31
}
32
]
33