node.js--web服务器
目前最主流的三个Web服务器是Apache
、Nginx
、IIS
。
使用 Node 建立 Web 服务器
如下是演示一个最基本的 HTTP 服务器架构(使用8081端口),建立 server.js 文件,代码以下所示:
var http = require('http');
var fs = require('fs');
var url = require('url');
// 建立服务器
http.createServer( function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;
// 输出请求的文件名
console.log("Request for " + pathname + " received.");
// 从文件系统中读取请求的文件内容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 响应文件内容
response.write(data.toString());
}
// 发送响应数据
response.end();
});
}).listen(8081);
// 控制台会输出如下信息
console.log('Server running at http://127.0.0.1:8081/');
接下来咱们在该目录下建立一个 text.htm 文件,代码以下:
<html>
<title></title>
<meta></meta>
<body>
<h3>hello welcome</h3>
</body>
</html>
执行 server.js 文件:
$ node server.js
Server running at http://127.0.0.1:8081/
结果以下:

其中server.js的读取文件代码须要注意一下:
fs.readFile(pathname.substr(1), function (err, data{})
pathname的输出值是/text.html
pathname.substr(1)指的就是text.html