简体   繁体   中英

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. 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.

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.

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-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 install file-type

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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