Created
January 9, 2020 17:42
-
-
Save luan0ap/521325c619413a02a798482e2c06af90 to your computer and use it in GitHub Desktop.
Convert a readable stream to base64 string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert a Readable Stream to base64 string | |
* @param {ReadableStream} stream - a readable stream to convert in base64 string | |
* @returns {Promise} - Promise that resolve in a string containing the base64 | |
*/ | |
const streamToBase64 = (stream) => { | |
const concat = require('concat-stream') | |
const { Base64Encode } = require('base64-stream') | |
return new Promise((resolve, reject) => { | |
const base64 = new Base64Encode() | |
const cbConcat = (base64) => { | |
resolve(base64) | |
} | |
stream | |
.pipe(base64) | |
.pipe(concat(cbConcat)) | |
.on('error', (error) => { | |
reject(error) | |
}) | |
}) | |
} | |
// Example: https://repl.it/@luan0ap/streamToBase64 |
Hello, when I am trying to convert the stream to base64 by using above code it will give an error .
TypeError: stream.pipe is not a function. (In 'stream.pipe(base642)', 'stream.pipe' is undefined)
This is a Node API. In the browser, you would do something like that (Typescript):
export async function readAsDataUri(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('loadend', (e) => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject(reader.error);
}
});
reader.readAsDataURL(file);
});
}
To only get the base64 string, you need to split and get the latter part.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kaushal9808 Hello, sorry for the late answer. You must ensure that the required param is a ReadableStream