Skip to content

Instantly share code, notes, and snippets.

@lgmcolin
Created January 17, 2014 08:01
Show Gist options
  • Save lgmcolin/8469890 to your computer and use it in GitHub Desktop.
Save lgmcolin/8469890 to your computer and use it in GitHub Desktop.
node 简单文件复制
var fs = require('fs'),
path = require('path');
exports.merge = function(src,des,cb){
if(!cb) cb = function(){}
var src = path.resolve(src),
des = path.resolve(des);
if(src.indexOf(des)){
return cb(new Error('error'));
}
fs.stat(src,function(err,stat){
if(err&&err.code !=='ENOENT'){
return cb(err);
}
_merge = function(src,des){
fs.mkdir(des,function(err){
if(err&&err.code!=='EEXIST'){
return cb(err);
}
var files = fs.readdirSync(src),
len = files.length;
for(var i=0;i<len;i++){
(function(i){
var srcPath = path.join(src,files[i]),
desPath = path.join(des,files[i]),
stat = fs.statSync(srcPath);
if(stat.isDirectory()){
_merge(srcPath,desPath);
}else{
fs.stat(desPath,function(err,stat)){
if(!err&&!stat.isDirectory()){
var readStream = fs.createReadStream(srcPath);
var writeStream = fs.createWriteStream(desPath);
readStream.pipe(writeStream);
cb();
}else{
cb(err);
}
}
}
)(i);
};
);
}
_merge(src,des);
});
}
//调用方式
var fsUtils = require('');
fsUtils.merge('d1','d2',function(err){
if(err){
console.log(err.toString());
}else{
console.log('done');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment