You can use the file-type
:
npm install file-type
Sample 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 => {
res.destroy();
console.log(fileType(chunk));
});
});
Upshot:
{ ext: 'png', mime: 'image/png' }
A way to check whether the url
contains the image in the format you want:
if (!(fileType(chunk).ext == "png")) {
console.log("deu ruim");
// aqui vem o seu return
}
Example taken from here.
I had never heard of this package, but as I will do the system in which case the URL is not an image the app gives
return
?– Gabriel
You will compare the result of
fileType(chunk)
with the formats you want to accept (png, jpg, etc.) instead of sending to the console - if it isfalse
, you give yourreturn
- what you think?– Daniel
@Gabriel Includes at the end of the answer a comparison with a type of extension.
– Daniel
if (!(filetype(Chunk).ext == "png")) { Typeerror: Cannot read Property 'ext' of null
– Gabriel
@Gabriel Tried with the url I put of example?
– Daniel
yes, then it worked, then I changed the URL to see if the Return code worked, and gave this.
– Gabriel
@Gabriel it might be interesting for you to open a new question by placing the code and error you are having - pq. I think you’ll change this question too much if you edit.
– Daniel
https://answall.com/questions/211351/erro-ao-usar-o-file-type
– Gabriel