简体   繁体   English

NodeJS:无法将流/缓冲区转换为base64字符串

[英]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. 我需要创建要发送给第三方API的base64字符串。 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. 无论我如何尝试,我都无法将它们转换为base64字符串。

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

None of the above works. 以上都不是。 Sometimes I get Uint8Array[arraySize] or Gibberish string. 有时我会收到Uint8Array [arraySize]或乱码。 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);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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