您的位置:首页 > Web前端 > Node.js

node.js入门【编一个小web服务器】

2015-04-29 09:43 561 查看

编写一个简单的web服务器

简单地说,一个web服务器最基本的功能就是能够根据客户端浏览器提供的http请求进行响应。

要使用你node.js的文件模块,需要使用require(“fs”)导入文件模块,下面是file模块的几个基本函数。

1.readfile(filename,[encoding],[callback])异步读取整个文件的内容

filename需要读取的文件名

encoding读取文件的编码格式,如果忽略,就返回数据缓冲区对象

callback读取文件的回调函数,该函数有两个参数,err和data,err反悔读取过程出现的错误。

var fs=require("fs");
fs.readFile("index.htm",function(err,data){
if(err)throw err;
else
console.log(data);

});


2.exits异步测试给定的文件或路径是否存在。

path:给定的文火煎或路径

callback:回调函数,有一个参数,返回true或false,表示给定的path是否存在。

var fs=require("fs");
fs.exists("index.htm",function(exists){

if(exists)console.log("file exists");
else
console.log("file not found");

});


3.现在我们可以完成一个简单的web服务器了。

创建一个server.js文件

var http=require("http"),
fs=require("fs"),
url=require("url");
//定义httpServer对象
var HttpServer=function(port){
//由http模块创建的httpserver对象
this.server=http.createServer(doRequest);
//服务器绑定的端口号
this.port=port;
//加载静态资源
function loadStaticResource(request,response)
{
//通过url解析请求中的url对象
var pURL=url.parse(request.url);
var fName=__dirname+pURL.pathname;
fs.exists(fName,function(exists){

if(exists){
fs.readFile(fName,function(err,data){

if(err)throw err;
else{
//设置mime内容类型
var contentType="text/html";
response.writeHead(200,{"Content-type":contentType});
response.write(data);
response.end();
}
});
}
else {
response.end("404 not found");
}

})
}
//响应静态请求
function doRequest(request,response){
loadStaticResource(request,response);

};

}

//设置httpserver对象的start方法
HttpServer.prototype.start=function()
{
this.server.listen(this.port);
console.log("listen"+this.port);

}
//创建httpserver
var server=new HttpServer(9001);
//启动server
server.start();


4.代码解析

首先导入3个常用的node.js模块,即http,fs和url模块,http模块主要提供http服务相关的功能,fs提供文件操作的功能,url提供了对url的解析功能。

导入了所需的模块后,定义了一个httpserver的函数对象,该对象定义了两个属性,一个是server,用于指向通过http创建的服务器,一个是port,用于绑定监听的端口。

上面我就用了this.server和this.port。

在createserver的时候,把requestlisten函数指向了dorequest方法,在dorequest方法中调用了loadstaticresourse方法,在loadstaticresourse函数中做了这样几个操作:

首先,通过url.parse方法解析request中的url对象,解析后,可以通过url.pathname获取客户端请求的文件名。

然后,使用__dirname+url.parthname,获取请求文件在服务器中的绝对位置,__dirname是node.js中的全局变量,通过它可以找到当前执行脚本所在的路径。

最后,调用fs.exists方法检查用户请求的文件是否存在,如果存在,就读去该文件,通过response的write方法输出所有的文件内容到客户端浏览器中,否则输出404.

好了,建立一个index.html文件,然后访问浏览器http://localhost:9001/index.htm访问资源就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: