IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Node.js 的简易web服务器

    Shawphy发表于 2011-11-19 11:57:24
    love 0

    网上关于Node.js的介绍已经铺天盖地了,但我就没找到一个简单的web服务器给我做测试用。
    实际上Node.js只需要一个exe文件和一个js文件就可以搭建服务器了,用来随便测试页面之类的用起来比nginx还方便。所以我就随手写了一个简单的。只可用于http服务,没有更多功能的js文件。

    用起来很简单:
    1,先去 http://nodejs.org/下载最新的Node.js可执行的exe文件。比如: http://nodejs.org/dist/latest/node.exe
    2,把下面的代码保存为一个 server.js 文件,把它跟刚才下载到的 node.exe 文件放在一起。
    3,把server.js文件拖到node.exe文件上就OK了

    就这三步之后,整个目录下的文件都可以通过 http://127.0.0.1:8080/ 来访问了,测试用起来非常方便。

    其他系统下也如法炮制,官网上也有下载mac和linux的版本。

    var http = require("http"),
    	url  = require("url"),
    	path = require("path"),
    	fs   = require("fs");
    
    http.createServer(function (req, res) {
    	var 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, {"Content-Type": "text/html"});
    			res.end("<h1>404 Not Found</h1>");
    		}
    	});
    
    }).listen(8080, "127.0.0.1");
    
    console.log("Server running at http://127.0.0.1:8080/");
    



沪ICP备19023445号-2号
友情链接