-
-
Save keepitsimple/61ba37bd980846f22e3499b8ce39ae02 to your computer and use it in GitHub Desktop.
Stream-download a file with filename from response header (content-disposition) via got package.
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 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