Skip to content

Instantly share code, notes, and snippets.

@leizongmin
Last active December 17, 2015 10:39
Show Gist options
  • Save leizongmin/5596814 to your computer and use it in GitHub Desktop.
Save leizongmin/5596814 to your computer and use it in GitHub Desktop.
合并目录下的所有文件
/**
* 合并目录下的文件
*/
var fs = require('fs');
var path = require('path');
/**
* 遍历目录里面的所有文件
*
* @param {String} dir 目录名
* @param {Function} findOne 找到一个文件时的回调
* 格式:function (filename, stats, next)
* @param {Function} callback 格式:function (err)
*/
function eachFile (dir, findOne, callback) {
var THREAD_NUM = 1; // 并发数量
if (!callback) {
callback = findOne;
findOne = function (file, stats, next) {
next();
};
}
fs.stat(dir, function (err, stats) {
if (err) return callback(err);
findOne(dir, stats, function () {
if (stats.isFile()) {
return callback(null);
} else if (stats.isDirectory()) {
fs.readdir(dir, function (err, files) {
if (err) return callback(err);
for (var i = 0, len = files.length; i < len; i++) {
files[i] = path.join(dir, files[i]);
}
var finish = 0;
var threadFinish = function () {
finish++;
if (finish >= THREAD_NUM) return callback(null);
};
var next = function () {
var f = files.pop();
if (!f) return threadFinish();
eachFile(f, findOne, function (err, s) {
if (err) return callback(err);
next();
});
};
for (var i = 0; i < THREAD_NUM; i++) {
next();
}
});
}
});
});
}
/**
* 合并目录下的所有文件
*
* @param {String} dir
* @param {String} saveTo
* @param {Function} callback
*/
function mergeAllFiles (dir, saveTo, callback) {
eachFile(dir, function (f, s, next) {
if (!s.isFile()) return next();
console.log('合并文件:%s', f);
fs.readFile(f, function (err, data) {
if (err) return callback(err);
fs.appendFile(saveTo, data, next);
});
}, function (err) {
if (err) return callback(err);
callback(null, saveTo);
});
}
// 开始了
mergeAllFiles('/tmp/2013-5-17', '/tmp/2013-5-17-all.txt', function (err, f) {
if (err) throw err;
console.log('已保存到:%s', f);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment