在 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 上运行时,可以通过以下方式调用 .bat.cmd 文件:

🌐 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 by:

无论如何,如果脚本文件名包含空格,则需要加引号。

🌐 In any case, if the script filename contains spaces, it needs to be quoted.

const { exec, spawn } = require('node:child_process');

exec('my.bat', (err, stdout, stderr) => { /* ... */ });

// Or, spawning cmd.exe directly:
const bat = spawn('cmd.exe', ['/c', 'my.bat']);

// If the script filename contains spaces, it needs to be quoted
exec('"my script.cmd" a b', (err, stdout, stderr) => { /* ... */ });import { exec, spawn } from 'node:child_process';

exec('my.bat', (err, stdout, stderr) => { /* ... */ });

// Or, spawning cmd.exe directly:
const bat = spawn('cmd.exe', ['/c', 'my.bat']);

// If the script filename contains spaces, it needs to be quoted
exec('"my script.cmd" a b', (err, stdout, stderr) => { /* ... */ });