Error using file-type

Asked

Viewed 41 times

1

I had asked a question here yesterday, and the 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 that is not an image (and is at http) the following error is displayed:

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

TypeError: Cannot read property 'ext' of null

Could someone help me? Thanks in advance.

1 answer

2

In the little documentation, it is indicated that if the URL does not have an image with compatible format, 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.

So to resolve your question, I believe it’s enough before making the comparison, check 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 only not generate the error if the URL does not point to an image, just test first if the return is null, and if it is not, follows 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");
    });
});
  • But it’s general, isn’t it? I just want it not to Return when it’s not a PNG.

  • @Gabriel You can use the if only to prevent it from making a mistake - but you can continue with the program instead of giving return.

  • @Gabriel Please see my issue in reply (I tried to leave complete).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.