Http URL Validity can be checked in 2 ways.
- Using a regular expression to check if the pattern matches
- Ping to that URL and see if there is a response or not i.e. if it exists or not.
- var request = require('request');
- request.head(srcUrl, function(err, resp) {
- if(resp) {
- console.log('URL Valid');
- console.log(resp.headers);
- var option = {
- uri: srcUrl,
- encoding: null
- };
- request.get(option, function(err, resp, data) {
- if(!data){
- console.log('There is no data');
- } else {
- console.log(data);
- }
- }
- } else {
- console.log('Invalid URL');
- }
- }
Let's discuss about the above line by line.
- Line 1 is to include the node module 'request' into the current source.
- Line 2 checks for the headers. It makes a request to the url to get only the headers but not the actual data.
- Line 3 checks for a non-null response, it means that the URL is valid.
- Line 5 prints the response headers. At this point, the headers can be checked for the content type, content-length etc.. and the respective business logic can be implemented.
- Example: In order to check if the content is image, the following can be done
- if (/image\/.*/.test(resp.headers['content-type'])) { console.log('Content is Image'); }
- Line 10 makes a GET request to the URL and the data is retrieved.
No comments:
Post a Comment