【问题标题】:How do I create a variable file name with the request nodejs module?如何使用请求 nodejs 模块创建变量文件名?
【发布时间】:2016-06-22 15:59:56
【问题描述】:

请求节点模块:https://github.com/request/request 有一个示例,它只是获取响应,然后将其通过管道传输到可写文件流中。如果我有一个可变文件名怎么办?例如,如果链接可以是 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

【问题讨论】:

    标签: node.js request pipe response filenames


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你应该在回调中创建文件,因为回调在程序结束时运行,文件名基于 resType。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        相关资源
        最近更新 更多