在Windows
本地调试静态网页时, file://
的绝对路径根目录是系统盘的根目录, 并不是我们理想的根目录。
或者你在类似于Cloud Studio
这样没有自己提供实时展示的网页IDE, 对于调试来说会比较麻烦。
这时, 你可能会想要安装一个http服务器来帮助你调试网页. 但是安装一个完整的http服务器太麻烦了.
Cloud Studio
的网页IDE所提供的虚拟Ubuntu
环境没有自带http
服务器. Python
拥有自带的http服务器, 但是对于Python
一窍不通的我, 为了一个http服务器而安装Python
会很麻烦. npm
有一个http-server
,但是它功能很多, 只是调试静态网页的并不需要太多的功能.
如果你像我一样, 那么, 你可以使用这样一个基于Node.js
的小型http服务端.
这是源代码仓库链接:https://github.com/BovineBeta/mini-http-server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| console.time('start WebServer need time');
var libHttp = require('http'); var libUrl = require('url'); var libFs = require("fs"); var libPath = require("path");
var funGetContentType = function (filePath) { var contentType = ""; var ext = libPath.extname(filePath); switch (ext) { case ".html": contentType = "text/html"; break; case ".js": contentType = "text/javascript"; break; case ".css": contentType = "text/css"; break; case ".gif": contentType = "image/gif"; break; case ".jpg": contentType = "image/jpeg"; break; case ".png": contentType = "image/png"; break; case ".ico": contentType = "image/icon"; break; default: contentType = "application/octet-stream"; } return contentType; }
var funWebSvr = function (req, res) { var reqUrl = req.url; console.log(reqUrl); var pathName = libUrl.parse(reqUrl).pathname; if (libPath.extname(pathName) == "") { pathName += "/"; } if (pathName.charAt(pathName.length - 1) == "/") { pathName += "index.html"; } var filePath = libPath.join("./WebRoot", pathName); libFs.exists(filePath, function (exists) { if (exists) { res.writeHead(200, { "Content-Type": funGetContentType(filePath) }); var stream = libFs.createReadStream(filePath, { flags: "r", encoding: null }); stream.on("error", function () { res.writeHead(404); res.end("<h1>404 Read Error</h1>"); }); stream.pipe(res); } else { res.writeHead(404, { "Content-Type": "text/html" }); res.end("<h1>404 Not Found</h1>"); } }); }
var webSvr = libHttp.createServer(funWebSvr);
webSvr.on("error", function (error) { console.log(error); });
var port = 1234;
webSvr.listen(port, function () { console.log('WebServer running at http://127.0.0.1:' + port + '/'); console.timeEnd('start WebServer need time'); });
|
修改好端口与网站根目录后, 把它保存为.js
文件. 把网页放在网站根目录之后就可以用Node
运行它了.
大功告成, 你再也不用烦恼绝对路径的问题了.
这是该文章的另一个作者:Water Moelon.