您的位置:首页 > Web前端 > Node.js

Node.JS 循环递归复制文件夹目录及其子文件夹下的所有文件

2017-09-18 22:17 971 查看

实现代码一:

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)
}

复制目录及其子目录

var copyFolder = function(srcDir, tarDir, cb) {
fs.readdir(srcDir, function(err, files) {
var count = 0
var checkEnd = function() {
++count == files.length && cb && cb()
}
if (err) {
checkEnd()
return
}
files.forEach(function(file) {
var srcPath = path.join(srcDir, file)
var tarPath = path.join(tarDir, file)
fs.stat(srcPath, function(err, stats) {
if (stats.isDirectory()) {
console.log('mkdir', tarPath)
fs.mkdir(tarPath, function(err) {
if (err) {
console.log(err)
return
}
copyFolder(srcPath, tarPath, checkEnd)
})
} else {
copyFile(srcPath, tarPath, checkEnd)
}
})
})
//为空时直接回调
files.length === 0 && cb && cb()
})
}

使用时

copyFolder('...', '....', function(err) {
if (err) {
return
}
//continue
})

文章到此结束,希望有帮助的朋友多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息