//引入模块 var http = require(‘http‘), url = require(‘url‘), querystring = require(‘querystring‘), fs = require(‘fs‘), dns = require(‘dns‘); //展现填写页面。由res.end输出查询的form表单 var goIndex = function(req, res){ res.end("<html>" + "<head>" + "<title>DNS查询</title>" + "<meta http-equiv=‘content-type‘ content=‘text/html;charset=utf-8‘>" + "</head>" + "<body>" + "<form action=‘/parse‘ method=‘post‘>" + "<input type=‘text‘ name=‘search_dns‘/>" + "<input type=‘submit‘ value=‘查询‘ />" + "</form>" + "</body>" + "</html>"); }; //dns解析函数。通过dns模块的dns.resolve解析,解析成功执行回调,回调中把值写到参数函数的入参中 var goDns = function(postData, callback){ var domainValue = querystring.parse(postData).search_dns; //获取post数据中的search_dns dns.resolve(domainValue, function(err, addresses){ if(!addresses){ addresses = [‘域名不存在‘]; } callback(domainValue, addresses); }); }; //dns解析。获取post过来的数据,用dns模块进行解析,输出解析结果 var parseDns = function(req, res){ //读取post过来的数据 var postData = ‘‘; //req请求对象有addListener方法,‘data‘事件是有数据传送到服务端时触发,‘end‘是在数据发送完毕时触发 req.addListener(‘data‘, function(dataChunk){ postData += dataChunk; }); req.addListener(‘end‘, function(){//数据完全传送完毕,进行dns解析 goDns(postData, function(domain, addresses){//回调中输出解析结果展示页面 res.end("<html>" + "<head>" + "<meta http-equiv=‘content-type‘ content=‘text/html;charset=utf-8‘>" + "</head>" + "<div>" + "domain: <span>" + domain + "</span>" + "ip:" + addresses.join(‘,‘) + "</div>" + "</html>"); }); }); }; var router = function(req, res, pathname){ switch(pathname){ case ‘/parse‘ : parseDns(req, res); break; default : goIndex(req, res); } }; http.createServer(function(req, res){ //获取请求相对路径 var pathname = url.parse(req.url).pathname; //将请求设置为utf-8防止乱码 req.setEncoding(‘utf8‘); //写返回的头 res.writeHead(200, {‘Content-Type‘ : ‘text/html‘}); //router请求路径若为/parse则进行dns解析,若不是则展示填写页面 router(req, res, pathname); }) .listen(3000, ‘127.0.0.1‘);
参考:《node.js开发实战详解》清华大学出版社,此文可以看作是此书的读书笔记
时间: 2024-10-25 15:54:02