简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM