前端之家收集整理的这篇文章主要介绍了
Node.JS 循环递归复制文件夹目录及其子文件夹下的所有文件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_0@实现代码一:
<div class="jb51code">
<pre class="brush:js;">
var fs = require('fs')
var path = require('path')
var copyFile = function(srcPath,tarPath,cb) {
var rs = fs.createReadStream(srcPath)
rs.on('error',function(err) {
if (err) {
console.log('read error',srcPath)
}
cb && cb(err)
})
var ws = fs.createWriteStream(tarPath)
ws.on('error',function(err) {
if (err) {
console.log('write error',tarPath)
}
cb && cb(err)
})
ws.on('close',function(ex) {
cb && cb(ex)
})
rs.pipe(ws)
}
if (err) {
checkEnd()
return
}
files.forEach(function(file) {
var srcPath = path.join(srcDir,file)
var tarPath = path.join(tarDir,file)
fs.stat(srcPath,stats) {
if (stats.isDirectory()) {
console.log('mkdir',tarPath)
fs.mkdir(tarPath,function(err) {
if (err) {
console.log(err)
return
}
copyFolder(srcPath,checkEnd)
})
} else {
copyFile(srcPath,checkEnd)
}
})
})
//为空时直接回调
files.length === 0 && cb && cb()
})
}