NodeJS writeStream empty file



我正在尝试使用nodejs保存存储在base64字符串中的处理图像。

var buff = new Buffer(base64data,'base64');
console.log(base64data);
var stream = fs.createWriteStream('/path/to/thefile.png');
stream.write(buff)
stream.end()

但是,结果文件为空。

当我输入console.log(base64data);的输出并在本地解码时,它会产生有效的png二进制文件,那么为什么文件为空?

该文件是3600x4800 PX PNG文件(即很大),这是一个因素吗?

另外,我也尝试了writeFile,没有运气。

是的,fsrequire('fs')

谢谢

您的stream.end()太早了。它是异步函数记住。

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();
});

更好:

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) => {...});

最新更新