Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Created January 9, 2020 17:42
Show Gist options
  • Save luan0ap/521325c619413a02a798482e2c06af90 to your computer and use it in GitHub Desktop.
Save luan0ap/521325c619413a02a798482e2c06af90 to your computer and use it in GitHub Desktop.
Convert a readable stream to base64 string
/**
* 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
@luan0ap
Copy link
Author

luan0ap commented Feb 21, 2022

@kaushal9808 Hello, sorry for the late answer. You must ensure that the required param is a ReadableStream

@real-felix
Copy link

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