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
.
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));
Output looks like this :
[ { 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' } ]