NodeJS child_process: different results when using spawn and console

128 Views Asked by At

I'm trying to compress an image with pngquant. Here is the code:

  let output = '';
  const quant = cp.spawn('pngquant', ['256', '--speed', '10'], {
    stdio: [null, null, 'ignore'],
  });

  quant.stdout.on('data', data => output += data);

  quant.on('close', () => {
    fs.writeFileSync('image.png', output);
    fs.writeFileSync('image_original.png', image);
    process.exit(0);
  });

  quant.stdin.write(image);

image is a Buffer with pure PNG data. The code works, however, for some reason, it generates incorrect PNG. Not only that, but also it's size is more than original's.

When I execute this from the terminal, I get excellent output file:

pngquant 256 --speed 10 < image_original.png > image.png

I have no idea of what's going on; the data in output file seems pretty PNG-ish.

EDIT: I have managed to make it work:

let output = [];

quant.stdout.on('data', data => output.push(data));
quant.stdin.write(image);

quant.on('close', () => {
  const image = Buffer.concat(output);

  fs.writeFileSync('image.png', image);
});

I assume that is related to how strings are represented in the NodeJS. Would be happy to get some explanation.

0

There are 0 best solutions below