Search code examples
node.jsrequestpiperesponsefilenames

How do I create a variable file name with the request nodejs module?


The request node module: https://github.com/request/request has an example where it just gets the response and then pipes it into a writable file stream. What if I have a variable file name? For example if the link could be a png or a jpg? How do I pipe AFTER I get the response?

request.get('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

For example,

request.get(fileURL)
    .on('response', res => {
      let resType = res.headers['content-type'];
      //get the file name based on the content-type
    })
    .pipe(fs.createWriteStream(fileName); //should use the fileName created in the on('response') callback

Solution

  • You were really close. You just have to pipe inside that callback:

    let req = request.get(fileURL)
      .on('response', res => {
          let resType = res.headers['content-type'];
          let fileName = figureOutExtension(resType); //get the file name based on the content-type
          req.pipe(fs.createWriteStream(fileName));
        })