如何使用请求 nodejs 模块创建可变文件名?

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

请求节点模块:https://github.com/request/request 有一个示例,它只是获取响应,然后将其通过管道传输到可写文件流中。如果我有一个可变文件名怎么办?例如,如果 link 可以是 png 或 jpg?收到回复后如何进行管道传输?

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

例如,

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

你们真的很亲密。您只需要在该回调中进行管道传输:

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));
    })

你应该在回调中创建文件,因为回调是在这个程序的末尾 运行 并且文件名是基于 resType.