Node.JS发送http请求批量检查文件中的网页地址、服务是否有效可用
在node.js中只需要几行代码就可以发送http请求,通过检查statusCode可以判断该网址服务是否有效。
如下代码:
var http = require('http') var checkExists = function(urlPath, cb) { var options = { host: '192.168.2.101', port: 8064, path: encodeURI(urlPath)} var req = http.request(options, function(r) { cb && cb(r.statusCode == 200); }) req.end() }
以上代码检查相对网址是否可用,需手动修改服务器地址和端口,使用以下代码可以检查完整地址的可用性。
var http = require('http') var url = require('url') var checkUrlExists = function (Url, cb) { var options = { //method: 'HEAD', host: url.parse(Url).host, port: 80, path: url.parse(Url).pathname }; var req = http.request(options, function (r) { cb && cb( r.statusCode == 200); }); req.end(); }
搭配 fs 模块,可以指解析文件中的地址是否可用,完整代码如下:
var http = require('http') var url = require('url') var fs = require('fs') /* 检查完整网址是否可用 */ var checkUrlExists = function (Url, cb) { var options = { //method: 'HEAD', host: url.parse(Url).host, port: 80, path: url.parse(Url).pathname }; var req = http.request(options, function (r) { cb && cb( r.statusCode == 200); }); req.end(); } /* 检查相对网址是否可用,需修改服务器地址和端口 */ var checkExists = function(urlPath, cb) { var options = { host: '192.168.2.101', port: 8064, path: encodeURI(urlPath)} var req = http.request(options, function(r) { cb && cb(r.statusCode == 200); }) req.end() } var checkFile = function(filePath) { fs.readFile(filePath, function(err, data) { if (err) { console.log(err) return } var lines = data.toString().split(/[\r\n]+/) var curr = 0 var urlPath var checkNext = function(exist) { if (curr > lines.length - 1) { console.log('end') return } //console.log(curr, 'exist', exist, urlPath) if (!exist) { console.log(curr, 'exist', exist, urlPath) } if (curr >= lines.lines) { console.log('end') return } urlPath = lines[curr++] checkExists(urlPath, checkNext) } checkNext() }) } checkFile('./visit.csv')
总结
以上所述是小编给大家介绍的Node.JS发送http请求批量检查文件中的网页地址、服务是否有效可用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对安科网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
相关推荐
86193952 2020-10-27
knightwatch 2020-07-19
88407013 2020-06-16
标题无所谓 2020-06-10
小木兮子 2020-11-11
HeyShHeyou 2020-11-17
seanzed 2020-10-15
huangliuyu00 2020-09-24
libaoshan 2020-09-11
zhangpan 2020-09-10
chongxiaocheng 2020-08-16
xcguoyu 2020-08-15
Qizonghui 2020-08-02
ldcwang 2020-07-26
mqfcu 2020-07-21
jeason 2020-07-20
sunzhihaofuture 2020-07-19
点滴技术生活 2020-07-19