为了账号安全,请及时绑定邮箱和手机立即绑定

Base64编码后将axios图像流转换为字符串?

Base64编码后将axios图像流转换为字符串?

慕哥9229398 2022-06-05 09:47:35
到目前为止,我有这个:const Fs = require('fs')  const Path = require('path')  const Axios = require('axios')var {Base64Encode} = require('base64-stream');const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true'const response = await Axios({      url,      method: 'GET',      responseType: 'stream'    })response.data.pipe(new Base64Encode())这个base 64 对图像进行编码。我们怎样才能把它变成一个字符串。我试过这样的事情:  function streamToString (stream) {    const chunks = []    return new Promise((resolve, reject) => {      stream.on('data', chunk => chunks.push(chunk))      stream.on('error', reject)      stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))    })  }const result = await streamToString(response.data.pipe(new Base64Encode()))但它错误。想法?
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

在您的示例中,您使用了Base64encode已经抽出字符串的模块 - 这使得上面的示例失败(除非那是因为顶级等待)。您实际上不需要将块转换为字符串,因为它们已经是字符串,因此可以进行简单的串联。


事实上,仅使用 node.js 流,整个事情可能会简单 10 倍:


const Axios = require('axios')

const {PassThrough} = require("stream");


const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true';


(async function() {

    const response = await Axios({

        url,

        method: 'GET',

        responseType: 'stream'

    });


    // we just pipe the data (the input carries it's own encoding)

    // to a PassThrough node stream that outputs `base64`.

    const chunks = response.data

        .pipe(new PassThrough({encoding:'base64'}));


    // then we use an async generator to read the chunks

    let str = '';

    for await (let chunk of chunks) {

        str += chunk;

    }


    // et voila! :)

    console.log(str);

})();


查看完整回答
反对 回复 2022-06-05
  • 1 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号