在 Windows 上生成 .bat 和 .cmd 文件
【Spawning .bat and .cmd files on Windows】
child_process.exec() 与 child_process.execFile() 区分的重要性取决于平台。在类 Unix 操作系统(Unix、Linux、macOS)上,child_process.execFile() 可能更高效,因为它默认不会启动 shell。然而,在 Windows 上,.bat 和 .cmd 文件如果没有终端是无法单独执行的,因此无法使用 child_process.execFile() 启动。在 Windows 上运行时,可以使用 child_process.spawn() 并设置 shell 选项来调用 .bat 和 .cmd 文件,使用 child_process.exec(),或者通过启动 cmd.exe 并将 .bat 或 .cmd 文件作为参数传递(这也是 shell 选项和 child_process.exec() 的工作方式)。无论哪种情况,如果脚本文件名包含空格,需要使用引号引起来。
【The importance of the distinction between child_process.exec() and
child_process.execFile() can vary based on platform. On Unix-type
operating systems (Unix, Linux, macOS) child_process.execFile() can be
more efficient because it does not spawn a shell by default. On Windows,
however, .bat and .cmd files are not executable on their own without a
terminal, and therefore cannot be launched using child_process.execFile().
When running on Windows, .bat and .cmd files can be invoked using
child_process.spawn() with the shell option set, with
child_process.exec(), or by spawning cmd.exe and passing the .bat or
.cmd file as an argument (which is what the shell option and
child_process.exec() do). In any case, if the script filename contains
spaces it needs to be quoted.】
// OR...
const { exec, spawn } = require('node:child_process');
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
// Script with spaces in the filename:
const bat = spawn('"my script.cmd" a b', { shell: true });
// or:
exec('"my script.cmd" a b', (err, stdout, stderr) => {
// ...
});// OR...
import { exec, spawn } from 'node:child_process';
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
// Script with spaces in the filename:
const bat = spawn('"my script.cmd" a b', { shell: true });
// or:
exec('"my script.cmd" a b', (err, stdout, stderr) => {
// ...
});