Node.js 檔案系統操作需手動遞迴建立目錄,若需大量複製目錄結構,直接呼叫 Windows xcopy 指令最簡潔。但 child_process.exec() 直接執行 xcopy 常失敗,改寫入 .bat 檔再用 call 呼叫即可穩定運作。
var fs = require('fs'), path = require('path');
var dirCache = {};
function makedir(dir, callback) {
if (dirCache[dir]) { callback(); return; }
fs.exists(dir, function(exists) {
if (exists) { dirCache[dir] = true; callback(); }
else {
makedir(path.dirname(dir), function() {
fs.mkdir(dir, function() {
dirCache[dir] = true;
callback();
});
});
}
});
}
var fs = require('fs');
var exec = require('child_process').exec;
var cmdStr = 'xcopy D:\\WORK_new\\odinQuest D:\\WORK_new\\newGame /s /e /Q /Y /I';
// 寫入 .bat 檔
fs.writeFile('xcopy.bat', cmdStr, function(err) {
if (err) throw err;
// 以 call 呼叫批次檔
exec('call "' + process.cwd() + '/xcopy.bat"', function(err, stdout, stderr) {
if (err) console.error('exec error:', err);
else console.log('複製完成');
});
});
/s:複製目錄與子目錄(不含空目錄)/e:包含空目錄/Q:不顯示檔案名稱(安靜模式)/Y:覆寫不提示/I:目標不存在時假設為目錄