npm install async
var async = require('async');
var fs = require('fs');
process.chdir('file'); // 进入要遍历的文件夹
var concatenation = '';
var dirName = '.';
var dirContent = fs.readdirSync(dirName);
async.filter(dirContent, isFilename, function(filenames) {
async.forEachSeries(filenames, readAndConcat, onComplete);
});
function isFilename(filename, callback) {
// 不读取.开头的隐藏文件
if (filename[0] === '.') {
return;
}
console.log(filename);
fs.stat(filename, function(err, stats) {
if (err) throw err;
callback(stats.isFile() && [filename]);
});
}
function readAndConcat(filename, callback) {
fs.readFile(filename, 'utf8', function(err, fileContents) {
if (err) return callback(err);
concatenation += fileContents;
callback();
});
}
function onComplete(err) {
if (err) throw err;
console.log(concatenation);
}
网友评论