Skip to content

Instantly share code, notes, and snippets.

@HereComesJuju
Forked from adamwdraper/Node.js File Looper
Created July 23, 2019 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HereComesJuju/d5c6752dde75c7d66130f253ea8c0572 to your computer and use it in GitHub Desktop.
Save HereComesJuju/d5c6752dde75c7d66130f253ea8c0572 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