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

到目前为止,我有这个:


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()))

但它错误。想法?


慕哥9229398
浏览 167回答 1
1回答

月关宝盒

在您的示例中,您使用了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);})();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript