Created
January 17, 2014 08:01
-
-
Save lgmcolin/8469890 to your computer and use it in GitHub Desktop.
node 简单文件复制
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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