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访问资源就可以了。
相关文章推荐
- 学习用node.js建立一个简单的web服务器
- Node.js入门 ---构建一个Web程序
- Node.JS入门--通过构建一个上传文件的服务器来学习Node.JS
- Node.js 一个简单的Web服务器
- 建立一个node.js服务器(使用express搭建第一个Web环境)
- node.js搭建一个自己的本地web服务器
- 【node.js】使用node.js搭建一个本地web服务器
- 使用Node.js实现一个简单的FastCGI服务器实例
- 使用Node.js实现一个简单的FastCGI服务器实例
- Node.js的web服务器搭建与js的ajax交互
- 为一个 iOS 应用编写一个简单的 Node.js/MongoDB Web 服务
- nodejs + jquery Mobile构建一个简单的移动web ( 服务端index.js)
- (NodeJS学习文章收集三) node.js基于express框架搭建一个简单的注册登录Web功能
- node.js基础(创建web服务器)
- node.js入门 - 2.创建一个简单聊天室
- Node.js WEB服务器静态文件托管
- Node.js 入门手册:那些最流行的 Web 开发框架
- 分享一个基于 Node.js 的 Web 开发框架 - Nokitjs
- 浅析Node.js:一个“编码就绪”服务器