child_process 如果文件不存在,nodejs 不会触发错误

child_process nodejs doesn't fire error if file doesn't exists

我应该通过 Nodejs 执行 VBS 脚本,所以我正在使用 child_process.

我的问题是,如果生成过程出错,它永远不会触发错误事件。

const { spawn } = require( 'child_process' );

const vbs = spawn( 'cscript.exe', [ vbsPath] );
vbs.on('error', function( err ){
   console.log(err);
})
vbs.on('close', async function(code) {
   console.log(code)
});

vbsPath 是 vbs 的路径,如果我尝试输入错误的路径或在 vbs 中添加错误,它总是会触发 close 事件使用代码 1 而不是 0。 但我的问题是:

为什么它从不触发错误事件?关闭事件的 code 是否可靠以了解脚本是否 return 错误?

进程生成良好,因此您没有收到错误。

来自docs

The 'error' event is emitted whenever:

The process could not be spawned, or

The process could not be killed, or

Sending a message to the child process failed.

例如,如果您写入 const vbs = spawn('ciao', ['vbsPath']),您将收到错误事件。