Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stream-download a file with filename from response header (content-disposition) via got package.
const got = require('got');
const stream = require('stream');
const fs = require('fs');
const { promisify } = require('util');
const pipeline = promisify(stream.pipeline);
// instantiate the download stream - use options to set authorization header etc. if needed
let downStream = got.stream('https://example.com/download');
downStream.on('response', response => {
// response header will typically include the filename in content-disposition, like
// content-disposition:'attachment; filename="IMG_2358.JPG"'
let cd = response.headers['content-disposition'];
let filename = decodeURIComponent(cd.substring(cd.indexOf('=') + 2, cd.length - 1));
let outStream = fs.createWriteStream(filename);
pipeline(downStream, outStream)
.then(() => { /* ...handle success... */ })
.catch((err) => { /* ...handle error... */ });
});
downStream.on('error', err => {
// ...handle error...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment