复制
2023年06月10日
一、fs.cp()
const Fs = require("fs");
const Path = require("path");
const ignoreFileExtList = [".DS_Store", ".txt"];
const sourcePath = "/Users/zhangwenqiang/bolawen/scripts/test/a";
const targetPath = "/Users/zhangwenqiang/bolawen/scripts/test/e";
function copy(sourcePath, targetPath) {
return new Promise((resolve, reject) => {
Fs.cp(
sourcePath,
targetPath,
{
force: true,
recursive: true,
filter(src, desc) {
const pathInfo = Path.parse(src);
if (ignoreFileExtList.includes(pathInfo.ext)) {
return false;
}
return true;
},
},
(error) => {
if (error) {
return resolve(false);
}
resolve(true);
}
);
});
}
copy(sourcePath, targetPath);
二、child_process.exec
const { exec } = require("child_process");
const sourcePath = "/Users/zhangwenqiang/bolawen/scripts/test/a";
const targetPath = "/Users/zhangwenqiang/bolawen/scripts/test/e";
function execCmd(...args) {
return new Promise((resolve) => {
exec(args.join(" "), (error, stdout, stderr) => {
if (error) {
return resolve(false);
}
resolve(true);
});
});
}
async function copy(sourcePath, targetPath) {
await execCmd("cp", "-r", sourcePath, targetPath);
}
copy(sourcePath, targetPath);
三、child_process.spawn
const { spawn } = require("child_process");
const sourcePath = "/Users/zhangwenqiang/bolawen/scripts/test/a";
const targetPath = "/Users/zhangwenqiang/bolawen/scripts/test/e";
function spawnCmd(...args) {
return new Promise((resolve) => {
const childProcess = spawn(...args);
childProcess.stdout.pipe(process.stdout);
childProcess.stdout.pipe(process.stderr);
childProcess.on("close", () => {
resolve();
});
});
}
async function copy(sourcePath, targetPath) {
await spawnCmd("cp", ["-r", sourcePath, targetPath]);
}
copy(sourcePath, targetPath);