nodejs搭建本地http服务器

由于不做php相关的东西,懒得装apache,干脆利用nodejs搭建一个本地的服务器用于测试。

nodejs这玩意儿吧,对做前端的介入后端简直就是一把利器。而且目前,nodejs也越来越有商用价值。

nodejs其实是非常底层的,从功能上说,它既是apache也是php。像搭建http服务器这种功能,本来是apache已经封装好的,但nodejs需要我们手动来搭建。其实在实际应用中,我们可以使用现成的框架。但这里,我想手动搭建,也加深一下对http服务器的理解。

我们node执行下面这个文件,我命名为http.js,它将创建一个httpServer并监听3000端口。

var PORT = 3000;

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("assets", pathname);
    //console.log(realPath);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

上面我们还引入了一个mine.js,这是我自己写的,里面存储的是名值对,用于定义不同后缀的文件所对应的返回方式:

exports.types = {
  "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml"
};

fs模块是用于读取文件的,提供读取文件的方法,其实仔细研究文档会发现,它有同步和异步两种读取方式。fs.exists这个方法网上很多文章写作path.exists,,现在推荐写作fs.exists这个方法。否则会报警:

需要注意的是,不仅浏览器访问html文件会形成一次访问,里面链接的js,css等外部文件也会分别形成一次http访问。所以,http.createServer的回调其实是在一次页面访问中执行了多次的。我们console.log(realPath)一下就可以看到:

 

这里并没有加入默认访问index.html的功能,所以访问地址要写全http://127.0.0.1:3000/index.html

posted on 2013-06-06 14:48  shawn.xie  阅读(126988)  评论(6编辑  收藏  举报

导航

百度流量统计: