希望这篇文章能解决你这样一个问题:“我现在已经了解了一些Node.Js基本概念了,怎么搭一台静态服务器呢?”
请参考一下博主的前两篇文章:
本文实现的效果(样式就没做了,大家将就下):
列出的代码均测试可用,大家放心。
What is static server?
静态服务器,有了它呢,就可以让外部访问到咱们的静态网页。在功能上:它可以给用户发送文件(如:HTML, CSS, Js等)。正如上一篇文章所说:
Node.js本身并不是像IIS,Apache一样的webserver,它是一个JavaScript 的运行环境。所以,我们需要进行编码才能实现一个真正的京台服务器。
File stucture
后台目录建立如下,比较常规。大家可以随意定义目录结构,代码上相应地方改动一下就好。
app.js
本文的重点在于接下来的server模块,就不介绍app.js里的代码啦。(把主线代码写在app.js中是个不成文的约定,无需遵守,随意,随意。。。)
var http = require('http');var path = require('path');//引入我们自己编写的server模块var server = require('./server.js');http.createServer(function (request, response) { //以下的判断用来做简单的路由 if (request.url == "/") { filePath = path.join(__dirname, '/public/index.html'); } else { filePath = path.join(__dirname, '/public' + request.url); } server.serveStatic(response, filePath);}).listen(/*侦听4000端口*/4000, function () { console.log("Server listening on port 4000");});
MIME
静态服务器有一个必须实现的功能即为在HTTP报文中指定MIME type.
我们会引用一个第三方组件mime,通过npm安装,该组件可以根据文件的extension name映射mime type.
所以,请在根目录运行一下 npm install mime --save
server.js
var fs = require('fs');//provide the ability to derive a mime type based on the filename extensionvar mime = require('mime');var cache = {};//这不是IIS,Apache所以404必须自定义一下,function send404(response) { response.writeHead(404, { "Content-Type": "text/html" }); response.write("ERROR 404 FILE NOT FOUND
"); response.end();}//向客户端发送文件function sendFile(response, filePath, fileContents) { response.writeHead(200, { "Content-Type": mime.lookup(filePath) }); response.end(fileContents);}//这个函数导出,给主模块使用function serveStatic(response, absPath) { if (cache[absPath]) { sendFile(response, absPath, cache[absPath]); } else { fs.exists(absPath, function (exists) { if (exists) { fs.readFile(absPath, function (err, data) { if (err) { send404(response); } else { cache[absPath] = data; sendFile(response, absPath, data); } }); } else { send404(response); } }); }}exports.serveStatic = serveStatic;
解释部分如注释。。。至此,编码部分就完啦。
How to test
我们可以在./public 下放一个index.html 内容随意。。。node 跑起来后,只要输入 http://localhost:4000 返回的是它,输入http://localhost:4000/XXX 返回的是404,那么,静态服务器就搭起来了。
Summary
这个DEMO过于简单,应该不能满足大家胃口。以后会介绍如何搭一个动态的网站(以Restful service为例)。