實現代碼一:
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 })
文章到此結束,希望有幫助的朋友多多支持腳本之家。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com