Walking a directory with Node.js Walking a directory with Node.js javascript javascript

Walking a directory with Node.js


var path = dir + "/" + file;

You forgot to make path a local variable. Now it won't be changed behind your back in the loop.


Use node-dir for this. Because you need a separate action for directories and files, I'll give you 2 simple iterators using node-dir.

Asynchronously iterate the files of a directory and its subdirectories and pass an array of file paths to a callback.

var dir = require('node-dir');dir.files(__dirname, function(err, files) {  if (err) throw err;  console.log(files);  //we have an array of files now, so now we'll iterate that array  files.forEach(function(filepath) {    actionOnFile(null, filepath);  })});

Asynchronously iterate the subdirectories of a directory and its subdirectories and pass an array of directory paths to a callback.

var dir = require('node-dir');dir.subdirs(__dirname, function(err, subdirs) {  if (err) throw err;  console.log(subdirs);  //we have an array of subdirs now, so now we'll iterate that array  subdirs.forEach(function(filepath) {    actionOnDir(null, filepath);  })});


Another suitable library is filehound. It supports file filtering (if required), callbacks and promises.

For example:

const Filehound = require('filehound');function action(file) {  console.log(`process ${file}`)}Filehound.create().find((err, files) => {    if (err) {        return console.error(`error: ${err}`);    }    files.forEach(action);});

The library is well documented and provides numerous examples of common use cases. https://github.com/nspragg/filehound

Disclaimer: I'm the author.