title: Nodejs spawn stdout as api response
body: <p>I am writing a fastify post api which will take request, and then it will run a bat file with the request as the argument and I want to send the stdout from the spawn process to be sent as api response, one after another, like it shows in the terminal when you run the bat file normally in the terminal. Below is my code. If anyone could help, that would be amazing.</p>
  <pre><code>const fastify = require(&quot;fastify&quot;)({ logger: true });
  const { spawn } = require(&quot;child_process&quot;);
  var bat = require.resolve(&quot;./run.bat&quot;);
  
  //declare route
  
  fastify.post(&quot;/&quot;, async (request, reply) =&gt; {
    var { agent } = request.body;
    var { sub } = request.body;
    var { location } = request.body;
    var { times } = request.body;
    if (agent) {
      var scriptOutput = &quot;&quot;;
      var ls = spawn(bat, [agent, sub, location, times]);
      ls.stdout.setEncoding(&quot;utf8&quot;);
      ls.stdout.on(&quot;data&quot;, function (data) {
        console.log(&quot;stdout: &quot; + data);
        data = data.toString();
        scriptOutput += data;
      });
      ls.stderr.setEncoding(&quot;utf8&quot;);
      ls.stderr.on(&quot;data&quot;, function (data) {
        console.log(&quot;stderr: &quot; + data);
        data = data.toString();
        scriptOutput += data;
      });
      ls.on(&quot;exit&quot;, function (code) {
        console.log(&quot;child process exited with code &quot; + code);
        console.log(&quot;Full output of script: &quot;, scriptOutput);
        reply.send(scriptOutput);
      });
    } else {
      reply.code();
    }
  });
  
  //run server
  const start = async () =&gt; {
    try {
      await fastify.listen(3000);
    } catch (error) {
      fastify.log.error(error);
      process.exit(0);
    }
  };
  start();
  
  </code></pre>