How to create the write stream after the request response, when downloading a file from nodeJS?

46 Views Asked by At

I want to download a file from url, but i would like to get the file extension based on the MIME type of the response object before creating the writableStream that will pipe the data from the response on the filesystem. is there a way to accomplish this ?

export async function download(url: string, path: string) {

  await fs.mkdir(path, { recursive: true })

  // from this point, I do not know the MIME type of the response
  const fh = await fs.open(`${path}/file.${ ".??" }`, 'w')
  
  request
    .get(url)
    .pipe(fh.createWriteStream())
    .on('error', (error) => console.log(error))
    .on('finish', () => console.log('Download completed'))
}
0

There are 0 best solutions below