node.jslinuxspawnansi-colors

How to capture a colored spawned process output and send to the browser via nodejs?


I know there have been variations on this question, but none seem to cover this particular problem.

I am spawning a child process and attempting to send the output to the browser. The issue is the ansi coloring is not making it to the output.

I've imported ansi-to-html to render the ansi output if I receive it, but my spawned child is not preserving the output.

  const process = spawn(
    'bash',
   [
      '-ic',
      '<command I am running>'
   ],
    );

  process.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
    self.terminalOutput += convert.toHtml(`${data}`);

  });

  process.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
    self.terminalOutput += convert.toHtml(`${data}`);
  });

  process.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
    self.terminalOutput += convert.toHtml(`child process exited with code ${code}`)
  });

Solution

  • So it looks like I found an answer here. `${data}` was implicitly converting the the data returned from the spawned process (I believe by doing type conversion implicitly calling toString() but I could be wrong here).

    So to correctly pass the data to ansi-to-html, you must just pass it directly

      process.stdout.on('data', (data) => {
        self.terminalOutput += convert.toHtml(data);
      });
    
      process.stderr.on('data', (data) => {
        self.terminalOutput += convert.toHtml(data);
      });