Error using file-type

1

I had asked a question here yesterday, and Blogger helped me by passing this code:

const http = require('http');
const fileType = require('file-type');
const url = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png';

http.get(url, res => {
    res.once('data', chunk => {
      if (!(fileType(chunk).ext == "png")) {
    console.log("deu ruim");
    // aqui vem o seu return
}
        res.destroy();
        console.log(fileType(chunk));
    });
});

But when placing a URL where it is not an image (and is in http) the following error is displayed:

      if (!(fileType(chunk).ext == "png")) {
                           ^

TypeError: Cannot read property 'ext' of null

Can anyone help me? Thanks in advance.

    
asked by anonymous 08.06.2017 / 18:45

1 answer

2

In the small documentation , it is indicated that if the URL does not have a compatible format image, it returns null :

  

fileType (input)
  Returns an Object with:
  • ext - One of the supported file types
  • mime - The MIME type
  Or null when no match.

Then to solve your question, I believe that it is enough before comparing, checking if the return is null - if it is, the function ends there:

http.get(url, res => {
    res.once('data', chunk => {
        if (!fileType(chunk)) return;
        // ... comparação, resto do código
    });
});

Edit:

To just not generate the error if the URL does not point to an image, just test first if the return is null , and if not, proceed with the comparison:

const http = require('http');
const fileType = require('file-type');
const url = 'http://www.google.com';
// const url = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png';

http.get(url, res => {
    res.once('data', chunk => {
        if (fileType(chunk)) {
            if (!(fileType(chunk).ext == "png")) {
                console.log("alguma outra imagem");
            } else {
                console.log("imagem em png!");
            }
        } else {
            console.log("url não contem imagem");
        }
        console.log("a função continua aqui, pois não demos return");
    });
});
    
08.06.2017 / 20:26