Doug
Doug

Reputation: 869

NodeJS writeStream empty file

I am trying to use nodeJS to save a processed image stored in a base64 string.

var buff = new Buffer(base64data,'base64');
console.log(base64data);

var stream = fs.createWriteStream('/path/to/thefile.png');
stream.write(buff)
stream.end()

However, the resulting file is empty.

When I take the output of console.log(base64data); and decode it locally, it produces a valid png binary, so why is the file empty?

The file is a 3600x4800 px png file (i.e. it's huge), could this be a factor?

Also, I tried writeFile as well, no luck.

And yes, fs is require('fs')

Thanks

Upvotes: 11

Views: 13366

Answers (2)

Sergey Morzhov
Sergey Morzhov

Reputation: 79

Better:

var buff = new Buffer(base64data,'base64');
console.log(base64data);

var stream = fs.createWriteStream('/path/to/thefile.png');
stream.write(buff);
stream.end();
stream.on('finish', () => {
     //'All writes are now complete.'
});
stream.on('error', (error) => {...});

Upvotes: 6

wayne
wayne

Reputation: 3410

your stream.end() too soon as nothing is written. it is async function remember.

var buff = new Buffer(base64data,'base64');
console.log(base64data);

var stream = fs.createWriteStream('/path/to/thefile.png');
stream.write(buff);
stream.on("end", function() {
  stream.end();
});

Upvotes: 12

Related Questions