Skip to content

Instantly share code, notes, and snippets.

@tsmx
Last active October 6, 2022 13:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tsmx/c50735066e8105b3f91110b75686606d to your computer and use it in GitHub Desktop.
Save tsmx/c50735066e8105b3f91110b75686606d to your computer and use it in GitHub Desktop.
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