Skip to content

Instantly share code, notes, and snippets.

@facugon
Created June 25, 2024 19:47
Show Gist options
  • Save facugon/19bd4747a7b46e407e66cd2ce649a19f to your computer and use it in GitHub Desktop.
Save facugon/19bd4747a7b46e407e66cd2ce649a19f to your computer and use it in GitHub Desktop.
axios_stream_to_base64.js
const axios = require('axios')
const fs = require('fs')
const stream = require('stream')
const { promisify } = require('util')
const finished = promisify(stream.finished)
const download = async (url) => {
const response = await axios
.get(url, { responseType: 'stream' })
const chunks = []
const writable = new stream.Writable({
write(chunk, encoding, callback) {
chunks.push(chunk)
callback()
}
})
response.data.pipe(writable)
// new way
await finished(writable)
/*
* old way
*
* await new Promise((resolve, reject) => {
* writable.on('finish', resolve);
* writable.on('error', reject);
* });
*
*/
const buffer = Buffer.concat(chunks)
return buffer
}
const main = async (url) => {
const buffer = await download(url)
console.log(buffer)
console.log(buffer.toString('base64'))
}
main(process.argv.slice(2)[0])
@damianporchietto
Copy link

This saved my life, I actually jumped off a building and it transformed into a parachute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment