Created
June 25, 2024 19:47
-
-
Save facugon/19bd4747a7b46e407e66cd2ce649a19f to your computer and use it in GitHub Desktop.
axios_stream_to_base64.js
This file contains 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
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This saved my life, I actually jumped off a building and it transformed into a parachute.