由于 Node.js 是异步的,您需要等待子进程退出,然后再尝试对 result 进行操作。让我举例说明:
const spawn = require("child_process").spawn;
const process = spawn("python", ["./hello.py", 4]);
// A process was started in the background, and your code continues...
// You declare a `result` variable, whose value is `undefined`...
var result;
// Python might still be starting up at this point...
// You register a handler for output from the process, but it might not get called
// yet since your computer is from 1996 and it takes a while to start Python...
process.stdout.on("data", (data) => {
result = parseInt(data.toString());
});
// You operate on the `result`, which still is undefined...
var newNum = result * 10;
// Oh! Hey! Python started in the background! It printed out some data, and now the data handler from before got called! Yay! `result` is indeed 12 right now!
// but... you know... let's print `undefined * 10`.
console.log(newNum);
您可以改为等待标准输出流结束:
const spawn = require("child_process").spawn;
const process = spawn("python", ["./hello.py", 4]);
var result;
process.stdout.on("data", (data) => {
result = parseInt(data.toString());
});
process.stdout.on("end", () => {
var newNum = result * 10;
console.log(newNum);
});
或者进程退出:
const spawn = require("child_process").spawn;
const process = spawn("python", ["./hello.py", 4]);
var result;
process.stdout.on("data", (data) => {
result = parseInt(data.toString());
});
process.on("exit", () => {
var newNum = result * 10;
console.log(newNum);
});
您可以将其包装成一个简洁的帮助函数,该函数返回一个承诺(未经测试,抱歉):
const spawn = require("child_process").spawn;
function spawnAndCaptureOutput(command, args) {
return new Promise((resolve) => {
const process = spawn(command, args);
let stdout = "";
let stderr = "";
process.stdout.on("data", (data) => {
stdout += data.toString();
});
process.stderr.on("data", (data) => {
stderr += data.toString();
});
process.on("close", (code) => {
resolve({ stdout, stderr, code });
});
// TODO: error handling?
});
}
spawnAndCaptureOutput("python", ["./hello.py", 4]).then(
({ stdout }) => {
const number = parseInt(stdout);
console.log(number * 8);
},
);