使用node创建web服务器
模块
为了让node.js的文件互相调用,node.js提供了一个简单的模块系统。
模块是node.js应用程序的基本组成部分,模块和文件是一一对应的。换言之,一个文件就是一个模块,这个文件可以是,js文件,json数据、或者编译过的c/c++扩展。并且node.js附带了很多原生的模块,供开发者调用。http、fs就是其中重要的模块。
引入http模块
首先创建web服务器,需要引入node原生模块http,我们在我们的代码中请求它并把返回值附给本地变量http:
var http=require('http');
这里引入模块,简单介绍下node.js的模块系统:
引入fs模块
原生模块fs是node.js提供的一组类似unix标准的文件操作api,在本示例中用于读取文件内容。
var fs=require('fs');
引入url模块
url模块用于解析请求。
var url=require('url');
创建服务器
http.createServer(function(request,respose){
var pathname=url.parse(requst.url).pathname;
console.log('request for '+pathname+' receive');
fs.readFile(pathname.substr(1),function(err,data){
if(err)
{
respose.write(404,{'Content-Type':'text/html'});
}
else
{
respose.write(200,{'Content-Type':'text/html'});
respose.write(data.toString());
}
respose.end();
});
}).listen(8088);
console.log('server runing at 127.1.1 8080');
创建html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的第一个标题</h1>
<p>我的第一个段落。</p>
</body>
</html>
创建web客户端
var http = require('http');
// 用于请求的选项
var options = {
host: 'localhost',
port: '8080',
path: '/index.html'
};
// 处理响应的回调函数
var callback = function(response){
// 不断更新数据
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// 数据接收完成
console.log(body);
});
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();
运行
node server.js
node client.js