I'm doing an application in Node.js, and I want to make a custom background system using the URL given by the user, I would like to know how to check if the URL given by the user is an image, and if it is not , the application gives return
.
I'm doing an application in Node.js, and I want to make a custom background system using the URL given by the user, I would like to know how to check if the URL given by the user is an image, and if it is not , the application gives return
.
You can use 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));
});
});
Result:
{ext: 'png', mime: 'image / png'}
A way to check if 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 .