Skip to content

Instantly share code, notes, and snippets.

@adamwdraper
Created December 5, 2012 04:46
Show Gist options
  • Save adamwdraper/4212319 to your computer and use it in GitHub Desktop.
Save adamwdraper/4212319 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('-------------------------------------------------------------');
}
});
@pasqualederosa
Copy link

hi. I put the files into an array, and I want to return this array to another function?
How to do this.

@guicsou
Copy link

guicsou commented Nov 8, 2018

hi. I put the files into an array, and I want to return this array to another function?
How to do this.

Add your logic on line 29

@fuqinaz1
Copy link

works completely, thanks!

@Bravelemming
Copy link

Beautiful code. Thank you!

@jc9907
Copy link

jc9907 commented Mar 1, 2020

ur the fucking best

@Kawaritapas
Copy link

i want unzip files if zipped how to do it

@castrix
Copy link

castrix commented Nov 2, 2022

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment