Search code examples
node.jsencodingelectronwritefile

Node writeFileSync encoding options for images


I'm using fs.writeFileSync(file, data[, options]) to save a file returned from http.get(options[, callback])

This works fine for text files but images, pdfs etc end up being corrupted. From the searching around that I've done, it's apparently because fs.writeFileSync(file, data[, options]) defaults to UTF-8

I've tried setting the encoding to 'binary', the mime-type and the extension to no avail. It feels like something really obvious that I'm overlooking, can anyone point me in the right direction?

Thank you in advance

Update

I'm running this through electron. I didn't think it was worth mentioning as electron is just running node, but I'm not a node or electron expert so I'm not sure


Solution

  • Create a Buffer from the image data and set its encoding to binary. Then pass that data into a stream.PassThrough and pipe that into a stream.Writable.

    var fs = require('fs');
    var stream = require('stream');
    
    var imgStream = new stream.PassThrough();
    imgStream.end(Buffer.from(data, 'binary'));
    
    var wStream = fs.createWriteStream('./<dest>.<ext>');
    
    imgStream.once('end', () => {
        console.log('Image Written');
    });
    
    imgStream.once('error', (err) => {
        console.log(err);
    });
    
    imgStream.pipe(wStream);