读书人

node筹建简易服务器

发布时间: 2013-11-16 23:15:33 作者: rapoo

node搭建简易服务器

如果完全用node做所有服务器端的事情,http://expressjs.com/框架是一个很好的选择,不过我们也可以在一些简易的应用场景使用node

root # node server.js

如果server.js被修改后,需要重新启动服务器才能生效,这点很不方便,不过supervisor可以很好地解决

安装supervisor,它会监控目录的服务文件有无变化(如果编辑后文件有语法错误,服务就没法运行了,所以要特别注意)

npm install supervisor -g
root:~/test # supervisor server.jsDEBUG: Running node-supervisor withDEBUG:   program 'server.js'DEBUG:   --watch '.'DEBUG:   --ignore 'undefined'DEBUG:   --extensions 'node|js'DEBUG:   --exec 'node'DEBUG: Starting child process with 'node server.js'DEBUG: Watching directory '/root/test' for changes.Server running at http://127.0.0.1:8080/DEBUG: crashing childDEBUG: Starting child process with 'node server.js'Server running at http://127.0.0.1:8080/

简单的Hello World服务器(simple.js)

var http = require('http');// create http serverhttp.createServer(function (req, res) {                // content header                res.writeHead(200, {'content-type': 'text/plain'});                // write message and signal communication is complete                res.end("Hello, World!\n");                }).listen(8124);console.log('Server running on 8124/');

简单的http客户端(client.js)

var http = require('http');//The url we want, plus the path and options we needvar options = {host: 'localhost',      port: 8124,      path: '/?file=secondary',      method: 'GET'};var processPublicTimeline = function(response) {        // finished? ok, write the data to a file        console.log('finished request' + response);        console.log('STATUS: ' + response.statusCode);        console.log('HEADERS: ' + JSON.stringify(response.headers));        response.on('data', function (chunk) {                        console.log('BODY: ' + chunk);                        });};for (var i = 0; i < 5; i++) {        // make the request, and then end it, to close the connection        http.request(options, processPublicTimeline).end();}

post数据代码如下

var http = require('http'),    qs = require('qs');//The url we want, plus the path and options we needvar options = {    host: '127.0.0.1',    port: 8080,    path: '/add',    method: 'POST'};var postdata = qs.stringify({username:"User",password:"Password"});var processPublicTimeline = function(response) {        var body='';        response.on('data', function (chunk) {                body += chunk;        });        response.on('end',function() {                console.log(body);        });        response.on('error', function(e) {                console.log('problem with request: ' + e.message);        });};var req = http.request(options, processPublicTimeline);req.write(postdata);req.end();

复杂服务器:支持静态文件服务以及自定义handler处理

var http = require("http"),    url  = require("url"),    path = require("path"),    fs   = require("fs");var handle = {}handle["/"]            = rootHandler;handle["/add"]         = addHandler;handle["/save"]        = saveHandler;http.createServer(function (req, res) {    var pathname=url.parse(req.url).pathname;    if(typeof handle[pathname] === "function"){    handle[pathname](res, req);    }    else {        pathname=__dirname+url.parse(req.url).pathname;        if (path.extname(pathname)=="") {            pathname+="/";        }        if (pathname.charAt(pathname.length-1)=="/"){            pathname+="index.html";        }        fs.exists(pathname,function(exists){            if(exists){                switch(path.extname(pathname)){                case ".html":                    res.writeHead(200, {"Content-Type": "text/html"});                    break;                case ".js":                    res.writeHead(200, {"Content-Type": "text/javascript"});                    break;                case ".css":                    res.writeHead(200, {"Content-Type": "text/css"});                    break;                case ".gif":                    res.writeHead(200, {"Content-Type": "image/gif"});                    break;                case ".jpg":                    res.writeHead(200, {"Content-Type": "image/jpeg"});                    break;                case ".png":                    res.writeHead(200, {"Content-Type": "image/png"});                    break;                default:                    res.writeHead(200, {"Content-Type": "application/octet-stream"});                }                    fs.readFile(pathname,function (err,data){                    res.end(data);                });            } else {                res.writeHead(404, '404 Not Found', {'Content-Type': 'text/html'});                res.end('<h1>404 Not Found</h1>');            }        });    }}).listen(8080, "0.0.0.0");console.log("Server running at http://0.0.0.0:8080/");function rootHandler(res, req){    res.end("root");}function addHandler(res, req){//获取post数据    if(req.method == 'POST'){        var body = '';        req.on('data', function (data) {            body += data;        });        req.on('end', function () {            var POST = qs.parse(body);            console.log(POST);        });    }    res.end("add");}function saveHandler(res, req){    res.end("save");}

?

读书人网 >编程

热点推荐