user1640256
user1640256

Reputation: 1719

NodeJS: Unable to convert stream/buffer to base64 string

I need to create base64 string that I need to send to a third party API. I have the stream and buffer. Form stream I am able to create an image so there is no way the stream is corrupted. Here are the two variables:

var newJpeg = new Buffer(newData, "binary");

var fs = require('fs');
let Duplex = require('stream').Duplex;

let _updatedFileStream = new Duplex();
_updatedFileStream.push(newJpeg);
_updatedFileStream.push(null); 

No matter whatever I try, I can not convert either of them in base64 string.

_updatedFileStream.toString('base64');
Buffer(newJpeg, 'base64');
Buffer(newData, 'base64');

None of the above works. Sometimes I get Uint8Array[arraySize] or Gibberish string. What am I doing wrong?

Upvotes: 4

Views: 5946

Answers (1)

greuze
greuze

Reputation: 4398

Example using promises (but could easily be adapted to other approaches):

return new Promise((resolve, reject) => {
    let buffers = [];
    let myStream = <...>;
    myStream.on('data', (chunk) => { buffers.push(chunk); });
    myStream.once('end', () => {
        let buffer = Buffer.concat(buffers);
        resolve(buffer.toString('base64'));
    });
    myStream.once('error', (err) => {
        reject(err);
    });
});

Upvotes: 8

Related Questions