Nodejs порождает stdout в качестве ответа api

#node.js #stdout #spawn #fastify

Вопрос:

Я пишу api fastify post, который примет запрос, а затем запустит файл bat с запросом в качестве аргумента, и я хочу отправить вывод из процесса создания, который будет отправлен в качестве ответа 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();

 

Ответ №1:

вы проверили права на выполнение файла bat? Попробуй:

 chmod  x run.bat
 

если это поможет.