axios图片流Base64编码后转成字符串?
Turning an axios image stream into a string after Base64 Encoding it?
到目前为止我有这个:
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()))
但是它出错了。想法?
在您的示例中,您使用了已经输出字符串的 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);
})();
到目前为止我有这个:
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()))
但是它出错了。想法?
在您的示例中,您使用了已经输出字符串的 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);
})();