来自the official documentation of spawnSync
:
Returns: <Object>
pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.
每当发生错误时,我都会看到status
字段的值为1而不是0。
这对于检测错误很有用,但是我仍然想依靠error
字段。
但是,无论“如何努力”,都不会出现error
字段!
这是我的测试脚本test.js
:
const child_process = require("child_process");
const result2 = child_process.spawnSync("node", ["test2.js"], {stdio: "inherit"});
const result3 = child_process.spawnSync("node", ["test3.js"], {stdio: "inherit"});
console.log(result2);
console.log(result3);
这是文件test2.js
:
xxx
这是文件test3.js
:
throw new Error("xxx");
这是我从命令行运行node test.js
时得到的:
C:\Users\Temp\Desktop\test2.js:1
xxx
^
ReferenceError: xxx is not defined
at Object.<anonymous> (C:\Users\Temp\Desktop\test2.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
C:\Users\Temp\Desktop\test3.js:1
throw new Error("xxx");
^
Error: xxx
at Object.<anonymous> (C:\Users\Temp\Desktop\test3.js:1:7)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
{ status: 1,
signal: null,
output: [ null, null, null ],
pid: 7884,
stdout: null,
stderr: null }
{ status: 1,
signal: null,
output: [ null, null, null ],
pid: 9028,
stdout: null,
stderr: null }
有人可以解释一下这是怎么回事吗?
详细说明我的实际目标:
我有一个主脚本,可以同步生成其他几个脚本(即,一个接一个)。
我希望能够(当然在某些条件下)在每个脚本中抛出Error
个对象,然后在主脚本中捕获这些对象。
非常感谢您!