node.js - Nodejs 生成标准输出作为 api 响应
问题描述
我正在编写一个fastify post api,它将接受请求,然后它将以请求作为参数运行一个bat文件,我想从spawn进程发送stdout作为api响应发送,一个接一个,喜欢它当您在终端中正常运行 bat 文件时,会在终端中显示。下面是我的代码。如果有人可以提供帮助,那就太棒了。
const fastify = require("fastify")({ logger: true });
const { spawn } = require("child_process");
var bat = require.resolve("./run.bat");
//declare route
fastify.post("/", async (request, reply) => {
var { agent } = request.body;
var { sub } = request.body;
var { location } = request.body;
var { times } = request.body;
if (agent) {
var scriptOutput = "";
var ls = spawn(bat, [agent, sub, location, times]);
ls.stdout.setEncoding("utf8");
ls.stdout.on("data", function (data) {
console.log("stdout: " + data);
data = data.toString();
scriptOutput += data;
});
ls.stderr.setEncoding("utf8");
ls.stderr.on("data", function (data) {
console.log("stderr: " + data);
data = data.toString();
scriptOutput += data;
});
ls.on("exit", function (code) {
console.log("child process exited with code " + code);
console.log("Full output of script: ", scriptOutput);
reply.send(scriptOutput);
});
} else {
reply.code();
}
});
//run server
const start = async () => {
try {
await fastify.listen(3000);
} catch (error) {
fastify.log.error(error);
process.exit(0);
}
};
start();
解决方案
您是否检查了 bat 文件的执行权限?尝试:
chmod +x run.bat
如果这有帮助。