-
-
Save sorcamarian/5411d1ad0fa23ce3d434163d5ae3c68b to your computer and use it in GitHub Desktop.
Loop through all files in a given directory with node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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