nodejs搭建本地http服务器

本文转载自:http://www.cnblogs.com/shawn-xie/archive/2013/06/06/3121173.html

 

由于不做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这个方法。否则会报警:

nodejs搭建本地http服务器

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

nodejs搭建本地http服务器

 

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


如果根目录默认访问index.html的话可以用下面这段代码:

if (pathName.charAt(pathName.length - 1) == "/") {

            //如果访问目录

            pathName += "index.html"; //指定为默认网页

        }

 

另外,如果想提供下载文件功能可以使其他扩展名的文件使用"application/octet-stream"来做返回类型。

你可能感兴趣的:(HTTP服务器)