Skip to content

Instantly share code, notes, and snippets.

@sorcamarian
Forked from adamwdraper/Node.js File Looper
Created March 26, 2019 13:24
Show Gist options
  • Save sorcamarian/5411d1ad0fa23ce3d434163d5ae3c68b to your computer and use it in GitHub Desktop.
Save sorcamarian/5411d1ad0fa23ce3d434163d5ae3c68b to your computer and use it in GitHub Desktop.
Loop through all files in a given directory with node.js
var fs = require('fs');
var walkPath = './';
var walk = function (dir, done) {
fs.readdir(dir, function (error, list) {
if (error) {
return done(error);
}
var i = 0;
(function next () {
var file = list[i++];
if (!file) {
return done(null);
}
file = dir + '/' + file;
fs.stat(file, function (error, stat) {
if (stat && stat.isDirectory()) {
walk(file, function (error) {
next();
});
} else {
// do stuff to file here
console.log(file);
next();
}
});
})();
});
};
// optional command line params
// source for walk path
process.argv.forEach(function (val, index, array) {
if (val.indexOf('source') !== -1) {
walkPath = val.split('=')[1];
}
});
console.log('-------------------------------------------------------------');
console.log('processing...');
console.log('-------------------------------------------------------------');
walk(walkPath, function(error) {
if (error) {
throw error;
} else {
console.log('-------------------------------------------------------------');
console.log('finished.');
console.log('-------------------------------------------------------------');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment