const fs = require('fs');
// 同步阻塞(腳本、CLI 工具適用)
fs.cpSync('./src', './dist', { recursive: true, force: true });
// 非同步(伺服器、建構工具適用)
await fs.promises.cp('./src', './dist', { recursive: true, force: true });
const fs = require('fs');
const path = require('path');
async function copyDir(src, dest, options = {}) {
const { filter, onFile, concurrency = 8 } = options;
await fs.promises.mkdir(dest, { recursive: true });
const entries = await fs.promises.readdir(src, { withFileTypes: true });
const limit = pLimit(concurrency); // 需安裝 p-limit 或自寫簡易佇列
await Promise.all(entries.map(entry => limit(async () => {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (filter && !filter(srcPath, destPath)) return;
if (entry.isDirectory()) {
await copyDir(srcPath, destPath, options);
} else {
await fs.promises.copyFile(srcPath, destPath);
onFile?.(srcPath, destPath);
}
})));
}
// 使用
await copyDir('./src', './dist', {
filter: (src) => !src.includes('node_modules') && !src.endsWith('.map'),
onFile: (s, d) => console.log(`Copied: ${path.relative(process.cwd(), s)}`)
});
const { spawn } = require('child_process');
const path = require('path');
function copyWithSystemCmd(src, dest) {
return new Promise((resolve, reject) => {
const isWin = process.platform === 'win32';
const cmd = isWin ? 'robocopy' : 'cp';
const args = isWin
? [src, dest, '/E', '/COPY:DAT', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS']
: ['-R', '--preserve=timestamps', src, dest];
const proc = spawn(cmd, args, { windowsVerbatimArguments: true });
let stderr = '';
proc.stderr.on('data', d => stderr += d);
proc.on('close', code => {
// robocopy: 0~7 正常,≥8 錯誤
if (isWin ? code >= 8 : code !== 0) reject(new Error(stderr));
else resolve();
});
});
}
| 方案 | Node 版本 | 跨平台 | 效能 | 功能豐富度 | 適用場景 |
|---|---|---|---|---|---|
| `fs.cpSync/cp` | ≥16.7 | ✅ 完美 | ⭐⭐⭐⭐⭐ (系統級) | 過濾、保留時間、符號連結 | **首選**,所有新專案 |
| 手寫遞迴 | ≥10 | ✅ 完美 | ⭐⭐⭐ (JS 層面) | 可自訂邏輯、進度、並發控制 | 舊版 Node、需精細控制 |
| `spawn cp/xcopy/robocopy` | 所有 | ❌ 需分平台 | ⭐⭐⭐⭐ (系統級) | robocopy 功能最強(鏡像、重試、日誌) | Windows 大量檔案、需 robocopy 進階參數 |
| 第三方庫 (fs-extra, ncp) | 所有 | ✅ | ⭐⭐⭐ | API 豐富 | 舊專案維護、不想升級 Node |
Node.js 16.7+ 專案**直接用 `fs.cpSync` / `fs.cp`**,一行代碼解決跨平台遞迴複製,效能最強、API 最乾淨。舊版環境手寫遞迴或用 `fs-extra`。只有 Windows 大檔案鏡像、需 `robocopy` 斷點續傳/日誌/多執行緒時,才考慮 `child_process` 呼叫系統指令。