NodeJS:无法将流/缓冲区转换为 base64 字符串 [英] NodeJS: Unable to convert stream/buffer to base64 string
本文介绍了NodeJS:无法将流/缓冲区转换为 base64 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建需要发送到第三方 API 的 base64 字符串.我有流和缓冲区.表单流 我能够创建图像,因此流不会被破坏.这是两个变量:
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);
无论我尝试什么,我都无法将它们中的任何一个转换为 base64 字符串.
No matter whatever I try, I can not convert either of them in base64 string.
_updatedFileStream.toString('base64');
Buffer(newJpeg, 'base64');
Buffer(newData, 'base64');
以上都不起作用.有时我会得到 Uint8Array[arraySize] 或乱码字符串.我做错了什么?
None of the above works. Sometimes I get Uint8Array[arraySize] or Gibberish string. What am I doing wrong?
推荐答案
使用 Promise 的示例(但可以很容易地适应其他方法):
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);
});
});
这篇关于NodeJS:无法将流/缓冲区转换为 base64 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文