標籤:style blog http color io os ar for 資料
//引入模組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開發實戰詳解》清華大學出版社,此文可以看作是此書的讀書筆記
node.js--dns解析demo