简体   繁体   English

Node.js和Request.js:查找下载的文件扩展名?

[英]Node.js and Request.js: Finding the file extension for a download?

I'm trying to download a couple of files using request , but I don't know how to find what their extensions are. 我正在尝试使用request下载几个文件,但是我不知道如何找到它们的扩展名。 Some of them are images, some are sounds, some are videos, but all of them come from a URL with no extension at the end. 其中有些是图像,有些是声音,有些是视频,但是它们全部来自没有结尾的URL。

const request = require("request");

request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.pipe(fs.createWriteStream("files/what.extension"));

When you go on this website, it downloads just fine. 当您访问该网站时,它下载得很好。 Think of something like Google Drive links. 想想类似Google云端硬盘链接的东西。

I can't open any of these files unless they have a valid extension, so I'd appreciate some help. 除非它们具有有效的扩展名,否则我无法打开其中的任何文件,因此,我希望能提供一些帮助。

The response from the website should send the type of file through a header , most likely content-disposition or 网站的回复应通过标头,最可能的content-disposition

content-type


const request = require("request");
request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.on('response',  function (res) {
  res.pipe(fs.createWriteStream("files/what." + res.headers['content-type'].split('/')[1])); 
 // it could also be content-dispostion or any other header, please check the headers first

});

File Type npm will solve your purpose. 文件类型 npm将解决您的目的。

npm install file-type npm安装文件类型

const fileType = require('file-type');
http.get(url, res => {
res.once('data', chunk => {
    res.destroy();
    console.log(fileType(chunk));
    //=> {ext: 'One of the supported file types', mime: 'The MIME type'}
});});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM