I am very new to server side programming and NodeJS
I need to 开发者_如何学Goread a directory recursively to get the file name of each file in this directory ( an array of file names ( relative paths) should be returned)
I think it is some thing very common so I am hoping if someone can share the code. Or just tell me the right methods to call. Thanks
Here is my first shot at it.
fs = require('fs');
function getDirectoryFiles(directory, callback) {
fs.readdir(directory, function(err, files) {
files.forEach(function(file){
fs.stat(directory + '/' + file, function(err, stats) {
if(stats.isFile()) {
callback(directory + '/' + file);
}
if(stats.isDirectory()) {
getDirectoryFiles(directory + '/' + file, callback);
}
});
});
});
}
getDirectoryFiles('.', function(file_with_path) {
console.log(file_with_path);
});
Of course instead of the console.log
in the callback handling function you could push the values in a global array.
You can do this easily with the files method of the node-dir module:
Install the module
npm install node-dir
Then the code is as simple as
var dir = require('node-dir');
dir.files(__dirname, function(err, files) {
if (err) throw err;
console.log(files);
});
This will recurse through all subdirectories and result will be an array of file paths.
Also this may help: do async task on each file recursively and execute callback when done
check out loaddir https://npmjs.org/package/loaddir
npm install loaddir
loaddir = require('loaddir')
allJavascripts = []
loaddir({
path: __dirname + '/public/javascripts',
callback: function(){ allJavascripts.push(this.relativePath + this.baseName); }
})
You can use fileName
instead of baseName
if you need the extension as well.
精彩评论