javascriptnode.jsrequestjs

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.


Solution

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