Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 358
Doug Avatar asked Nov 12 '12 04:11

Doug


2 Answers

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();
});
like image 96
wayne Avatar answered Nov 09 '22 06:11

wayne


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) => {...});
like image 23
Sergey Morzhov Avatar answered Nov 09 '22 07:11

Sergey Morzhov