server.js 代码
var http = require("http");
var fs = require("fs");
var url = require("url");
var port = process.argv[2];
if (!port) {
console.log("请指定端口号好不啦?\nnode server.js 8888 这样不会吗?");
process.exit(1);
}
var server = http.createServer(function (request, response) {
var parsedUrl = url.parse(request.url, true);
var pathWithQuery = request.url;
var queryString = "";
if (pathWithQuery.indexOf("?") >= 0) {
queryString = pathWithQuery.substring(pathWithQuery.indexOf("?"));
}
var path = parsedUrl.pathname;
var query = parsedUrl.query;
var method = request.method;
/******** 从这里开始看,上面不要看 ************/
console.log("有个傻子发请求过来啦!路径(带查询参数)为:" + pathWithQuery);
response.statusCode = 200;
//默认首页
const filePath = path === "/" ? "/index.html" : path;
const index = filePath.lastIndexOf(".");
//suffix是后缀
const suffix = filePath.substring(index);
const fileTypes = {
".html": "text/html",
".css": "text/css",
".js": "text/javascript",
".png": "image/png",
".jpg": "image/jpeg",
};
response.setHeader(
"Content-Type",
`${fileTypes[suffix] || "text/html"};charset=utf-8`
);
let content;
try {
content = fs.readFileSync(`./public${filePath}`);
} catch (error) {
content = "文件不存在";
response.statusCode = 404;
}
response.write(content);
response.end();
/******** 代码结束,下面不要看 ************/
});
server.listen(port);
console.log(
"监听 " +
port +
" 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:" +
port
);
-
注意:
-
const filePath = path === "/" ? "/index.html" : path;的意思是申明文件的路径赋值于路径,路径等于/的话,默认的让filePath等于/index.html,如果不是,就是path。
let content;
try {
content = fs.readFileSync(`./public${filePath}`);
} catch (error) {
content = "文件不存在";
response.statusCode = 404;
}
response.write(content);
意思是:try的意思是不确定会不会报错,catch是抓住的意思,申明一个content(内容),如果内容存在,则读取当前目录下的文件路径,否则抓住错误,内容为文件不存在,状态码404。
const index = filePath.lastIndexOf(".");
//suffix是后缀
const suffix = filePath.substring(index);
const fileTypes = {
".html": "text/html",
".css": "text/css",
".js": "text/javascript",
".png": "image/png",
".jpg": "image/jpeg",
};
response.setHeader(
"Content-Type",
`${fileTypes[suffix] || "text/html"};charset=utf-8`
);
- 意思:申明
index是.的文件路径中的下标,申明后缀从.的下标开始获得子字符串,申明文件类型(hash表)有... 。${fileTypes[suffix] || "text/html"};charset=utf-8文件类型对应的后缀或HTML(兜底值)