let http = require("http");
let ss = require("./StaticServer.js");
// 1.创建一个服务器实例对象
let server = http.createServer();
// 2.注册请求监听
server.on("request", function (req, res) {
let rootPath = "E:\\Users\\30315\\Desktop\\abc";
ss.StaticServer(req, res, rootPath);
});
// 3.指定监听的端口
server.listen(3000);
StaticServer.js 内容如下所示
let path = require("path");
let fs = require("fs");
let mime = require("./mime.json");
function readFile(req, res, rootPath) {
let filePath = path.join(rootPath, req.url);
let extName = path.extname(filePath);
let type = mime[extName];
if (type.startsWith("text")) {
type += "; charset=utf-8;";
}
res.writeHead(200, {
"Content-Type": type
});
fs.readFile(filePath, function (err, content) {
if (err) {
res.end("Server Error");
}
res.end(content);
});
}
exports.StaticServer = readFile;