【问题标题】:Turning an axios image stream into a string after Base64 Encoding it?Base64编码后将axios图像流转换为字符串?
【发布时间】:2024-01-02 18:55:01
【问题描述】:

到目前为止,我有这个:

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

但它出错了。想法?

【问题讨论】:

  • chunks.join("")替换Buffer.concat(chunks).toString('utf8')

标签: javascript node.js stream axios base64


【解决方案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);
})();

【讨论】:

    最近更新 更多