node搭建简易服务器

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

root # node server.js

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

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

npm install supervisor -g
root:~/test # supervisor server.js

DEBUG: Running node-supervisor with
DEBUG:   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 child
DEBUG: 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 server
http.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 need
var 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 need
var 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");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值