Create image from ArrayBuffer in Nodejs

Viewed 15254

I'm trying to create an image file from chunks of ArrayBuffers.

all= fs.createWriteStream("out."+imgtype);

for(i=0; i<end; i++){
    all.write(picarray[i]);
}

all.end();

where picarray contains ArrayBuffer chunks. However, I get the error
TypeError: Invalid non-string/buffer chunk.

How can I convert ArrayBuffer chunks into an image?

3 Answers

Array Buffer is browser supported which will be unsupportable for writing file, we need to convert to Buffer native api of NodeJs runtime engine.

This few lines of code will create image.

const fs = require('fs');
let data = arrayBuffer // you image stored on arrayBuffer variable;
data = Buffer.from(data);
fs.writeFile(`Assets/test.png`, data, err => { // Assets is a folder present in your root directory
      if (err) {
         console.log(err);
      } else {
         console.log('File created successfully!');
      }
}); 
Related