怎么样快速起一个静态服务?
可以使用 http-server
# 安装
$ npm install http-server -g
# 开启
$ http-server -c-1
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.8.196:8080
Hit CTRL-C to stop the server
但用代码怎么写一个 http 服务器?
废话不多说直接上代码
//a node web server.
var http = require("http");
var url = require("url");
var fs = require("fs");
var mimeTypes = {
css: { "Content-Type": "text/css" },
js: { "Content-Type": "text/javascript" },
png: { "Content-Type": "image/png" },
jpg: { "Content-Type": "image/jpeg" },
svg: { "Content-Type": "text/xml" },
};
function start() {
function onRequest(request, response) {
var params = url.parse(request.url, true),
pathname = params.pathname;
//静态资源服务器
//fs.readFile(filename,[options],callback);
if (pathname === "/") {
fs.readFile(__dirname + "/index.html", function (err, file) {
if (err) throw err;
response.write(file, "binary");
response.end();
});
} else {
fs.readFile(__dirname + pathname, "binary", function (err, file) {
if (err && err.code === "ENOENT") {
response.writeHead(404, { "Content-Type": "text/plain" });
response.write(err + "
");
response.end();
} else if (err) {
response.writeHead(500, { "Content-Type": "text/plain" });
response.write(err + "
");
response.end();
} else {
var type = pathname.slice(pathname.lastIndexOf(".") + 1);
if (mimeTypes[type]) {
response.writeHead(200, mimeTypes[type]);
}
//有callback字段则为jsonp请求。
if (params.query && params.query.callback) {
var str = params.query.callback + "(" + file + ")";
response.end(str);
} else {
response.end(file); //普通的json
}
}
});
}
}
var port = process.argv[2] || 3000;
http.createServer(onRequest).listen(port);
console.log("Server has started at port " + port);
}
start();
还缺功能:
- MIME 支持更加完善
- 路径是目录默认读 index.html
- 缓存支持
- 内容 Accept-Encoding 编码