5

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?

1

3 Answers 3

3

Have you tried first converting it into a node.js. Buffer? (this is the native node.js Buffer interface, whereas ArrayBuffer is the interface for the browser and not completely supported for node.js write operations).

Something along the line of this should help:

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

for(i=0; i<end; i++){
    var buffer = new Buffer( new Uint8Array(picarray[i]) );
    all.write(buffer);
}
all.end();
Sign up to request clarification or add additional context in comments.

Comments

3

after spending some time i got this, it worked for me perfectly.

as mentioned by @Nick you will have to convert buffer array you recieved from browser in to nodejs Buffer.

var readWriteFile = function (req) {
    var fs = require('fs');
        var data =  new Buffer(req);
        fs.writeFile('fileName.png', data, 'binary', function (err) {
            if (err) {
                console.log("There was an error writing the image")
            }
            else {
                console.log("The sheel file was written")
            }
        });
    });
};

1 Comment

Thanks to answer. One addition, Buffer is deprecated now, use Buffer.from() instead.
0

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!');
      }
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.