使用 node 建站需要使用 web 服务器, Web 服务器是基于网站架设的服务器, 我们需要将 node 创建的网站文件保存在 Web 服务器, 当用户浏览网页时需要从 Web 服务器存取数据.
node 创建网站时需要先构建 Web 服务器, 下面我们来看一下使用 node 创建文本服务器的方法.
使用 Node.JS 搭建 Web 服务器是学习 Node.JS 比较全面的入门教程, 因为实现 Web 服务器需要用到几个比较重要的模块: http 模块, 文件系统, url 解析模块, 路径解析模块, 以及 301 重定向技术等.
作为一个 Web 服务器应具备以下几个功能:
能显示以 .html/.htm 结尾的 Web 页面
能直接打开以 .JS/.CSS/.JSON/.text 结尾的文件内容
显示图片资源
自动下载以 .apk/.docx/.zip 结尾的文件
形如 http://xxx.com/a/b/ , 则查找 b 目录下是否有 index.HTML, 如果有就显示, 如果没有就列出该目录下的所有文件及文件夹, 并可以进一步访问.
形如 http://xxx.com/a/b, 则作 301 重定向到 http://xxx.com/a/b/ , 这样可以解决内部资源引用错位的问题.
引入需要用到的几个模块:
- // http 协议模块
- var http = require('http');
- // url 解析模块
- var url = require('url');
- // 文件系统模块
- var fs = require('fs');
- // 路径解析模块
- var path = require('path');
创建服务并在指定的端口监听:
- // 创建一个服务
- var httpServer = http.createServer(this.processRequest.bind(this));
- // 在指定的端口监听服务
- httpServer.listen(port, function() {
- console.log('[HttpServer][Start]','runing at http://' + ip +':' + port +'/');
- console.timeEnd('[HttpServer][Start]');
- });
在创建服务的时候需要传递一个匿名函数 processRequest 对请求进行处理, processRequest 接收两个参数, 分别是 request 和 response, request 对象中包含了请求的所有内容, response 是用来设置响应头以及对客户端做出响应操作.
- processRequest: function (request, response) {
- var hasExt =true;
- var requestUrl = request.url;
- var pathName = url.parse(requestUrl).pathname;
- // 对请求的路径进行解码, 防止中文乱码
- pathName = decodeURI(pathName);
- // 如果路径中没有扩展名
- if (path.extname(pathName) ==='') {
- // 如果不是以 / 结尾的, 加 / 并作 301 重定向
- if (pathName.charAt(pathName.length-1) !='/'){
- pathName +='/';
- var redirect ='http://' + request.headers.host + pathName;
- response.writeHead(301, {
- location: redirect
- });
- response.end();
- return ;
- }
- // 添加默认的访问页面, 但这个页面不一定存在, 后面会处理
- pathName +='index.html';
- hasExt =false;// 标记默认页面是程序自动添加的
- }
- // 获取资源文件的相对路径
- var filePath = path.join('http/webroot', pathName);
- // 获取对应文件的文档类型
- var contentType =this.getContentType(filePath);
- // 如果文件名存在
- fs.exists(filePath, function(exists) {
- if (exists) {
- response.writeHead(200, {'content-type': contentType});
- var stream = fs.createReadStream(filePath, {flags:'r', encoding:null});
- stream.on('error', function () {
- response.writeHead(500, {'content-type':'text/html'});
- response.end('<h1>500 Server Error</h1>');
- });
- // 返回文件内容
- stream.pipe(response);
- }else {// 文件名不存在的情况
- if (hasExt) {
- // 如果这个文件不是程序自动添加的, 直接返回 404
- response.writeHead(404, {'content-type':'text/html'});
- response.end('<h1>404 Not Found</h1>');
- }else {
- // 如果文件是程序自动添加的且不存在, 则表示用户希望访问的是该目录下的文件列表
- var HTML ="<head><meta charset='utf-8'></head>";
- try {
- // 用户访问目录
- var filedir = filePath.substring(0, filePath.lastIndexOf('\\'));
- // 获取用户访问路径下的文件列表
- var files = fs.readdirSync(filedir);
- // 将访问路径下的所以文件一一列举出来, 并添加超链接, 以便用户进一步访问
- for (var iin files) {
- var filename = files[i];
- HTML +="<div><a href='" + filename +"'>" + filename +"</a></div>";
- }
- }catch (e){
- HTML +='<h1 > 您访问的目录不存在 </h1>';
- }
- response.writeHead(200, {'content-type':'text/html'});
- response.end(HTML);
- }
- }
- });
- }
来源: http://www.css88.com/qa/node-js/12219.html