resquest.js pipe 数据流下载文件时, 如何自动获取文件后缀名并保存? 在哪一步加入?

发布于 2022-09-04 22:09:36 字数 833 浏览 8 评论 0

我想要在 fs.createWriteStream 之前获取到这个链接的后缀名
之后再 pipe 到这个数据流中保存文件.

Promise 的方式我试过, then 之后就是完整的 response, 不能写入数据流.
并且 fs.writeFile 方法我也试过了, 写入格式不正确.

注意哈: URL中没有文件后缀名

下面是代码

const fs = require('fs');
const Promise = require('bluebird');
const request = require('request');

let url = 'http://mmbiz.qpic.cn/mmbiz_jpg/D1Wza369eswnoapNaAdvtqygvMAnViaCLa8AMwwDZ4rebKrPvicxFf8zuibfialkPD3A7w8omWjicVm7GhFWcsibfGibw/0';
let file = fs.createWriteStream('file');

request
    .get(url)
    .on('response', function (response) {
        let type = response.headers['content-type']
        type = '.' + type.substring(type.lastIndexOf('/') + 1);
        console.log(type);
        // 在这里加是不可以的
    })
    .pipe(file)
    .on('end', function () {
        console.log('end')
    })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2022-09-11 22:09:36

楼上的回答亲测没有效果,写入的文件仍然没有后缀名。

原因:
.on("response", fun())里的函数是以回调形式调用的,pipe()的时候type的值仍然是空字符串没改变,createWriteStream()之后type才有值,以下是正解:

正解:

  const fs = require('fs');
  const request = require('request');
  const url = "someurl"
  const path = "somepath"
  const filename = "somefilename"
  let req = request.get(url).on("response", (response) => {
    type = response.headers["content-type"];
    type = type.substring(type.lastIndexOf("/") + 1);
    req.pipe(fs.createWriteStream(`${path}\\${filename}\\.${type}`));
    req.on("close", (err) => {
      // do something
    });
  });
善良天后 2022-09-11 22:09:36
let type = '';
request
    .get(url)
    .on('response', function (response) {
        type = response.headers['content-type']
        type = '.' + type.substring(type.lastIndexOf('/') + 1);
        console.log(type);
        // 在这里加是不可以的
    })
    .pipe(fs.createWriteStream('name'+type))
    .on('end', function () {
        console.log('end')
    })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文