'How to convert the Stream to base64 string for NodeJS in TypeScript
I'm using axis to download the image as following:
private async downloadImage(imageUrl: string): Promise<Stream> {
const response = await axios.get<Stream>(imageUrl, {
headers: {
'Content-Type': 'image/jpeg',
},
responseType: 'stream',
});
return response.data;
}
How can I convert the "Stream" object to "base64 string" I get from this RESTFul API in NodeJS? Because I need to attach this image to send the mail (by nodemailer) to the user. Example,
attachments: [
{
filename: 'image.jpg',
path: 'data:image/png;base64,[base64Image]',
cid: 'image',
},
],
How can I achieve it for NodeJS in TypeScript?
Solution 1:[1]
Finally, I find the method to convert it by pass through the Stream:
static async streamToBase64(stream: Stream): Promise<string> {
return new Promise((resolve, reject) => {
const cbConcat = (base64) => {
resolve(base64);
};
stream
.pipe(new Base64Encode())
.pipe(concat(cbConcat))
.on('error', (error) => {
reject(error);
});
});
}
However, the Stream could be used once... Anyone know how to clone it to consume it again?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | James Fu |
