nodejs创建web服务器
2019-11-19 本文已影响0人
Wrestle_Mania
const http = require("http");
http
.createServer((req, res) => {
res.write("fuck\n");
res.writeHead(200, { "Content-Type": "text/html;charset=utf8" });
res.end("fuck");
})
.listen(8080);
这样是返回不了内容的,不知道为啥子
const http = require("http");
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html;charset=utf8" });
res.write("fuck");
res.end("fuck");
})
.listen(8080);
对比下,这种写法才行
const http = require("http");
const fs = require("fs");
http
.createServer((req, res) => {
let pathname = req.url;
if (pathname === "/") {
pathname = "/index.html";
}
if (pathname !== "/favicon.ico") {
fs.readFile(`static${pathname}`, (err, data) => {
if (err) throw err;
res.write(data);
});
}
res.end("fuck");
})
.listen(8080);
这样写是会报错的,先执行了end,再执行write
const http = require("http");
const fs = require("fs");
http
.createServer((req, res) => {
let pathname = req.url;
if (pathname === "/") {
pathname = "/index.html";
}
if (pathname !== "/favicon.ico") {
fs.readFile(`static${pathname}`, (err, data) => {
if (err) throw err;
res.write(data);
res.end("fuck");
});
}
})
.listen(8080);
这样写才对(现在是没有设置任何响应头,让浏览器自动的去做)
上面任然是很粗略的版本,很多异常的情况没有考虑进去
const http = require("http");
const fs = require("fs");
const path = require("path");
const mime = require("mime");
const url = require("url");
http
.createServer((req, res) => {
let pathname = req.url;
if (pathname === "/") {
pathname = "/index.html";
}
if (pathname !== "/favicon.ico") {
pathname = url.parse(pathname).pathname;
fs.readFile(`static${pathname}`, (err, data) => {
if (err) {
fs.readFile("static/404.html", (err, data) => {
if (err) throw err;
res.writeHead(404, { "Content-Type": "text/html;charset=utf8" });
res.write(data);
res.end();
});
return false;
}
res.writeHead(200, {
"Content-Type": mime.getType(pathname) + ";charset=utf8"
});
res.write(data);
res.end();
});
}
})
.listen(8080);
稍微完整的版本
const http = require("http");
const fs = require("fs");
const url = require("url");
const path = require("path");
const events = require("events");
const mime = require("./model/mime");
const EventEmitter = new events.EventEmitter();
http
.createServer((req, res) => {
let pathname = url.parse(req.url).pathname;
if (req.url === "/") {
pathname = "/index.html";
}
if (req.url !== "/favicon.ico") {
fs.readFile(`static${pathname}`, (err, data) => {
if (err) {
fs.readFile("static/404.html", (err, data) => {
if (err) throw err;
res.end(data);
});
} else {
const extname = path.extname(pathname);
mime.getType(fs, EventEmitter, extname);
EventEmitter.on("mime_type", mimeType => {
res.writeHead(200, { "Content-Type": mimeType });
res.end(data);
});
}
});
}
})
.listen(8080);
exports.getType = (fs, EventEmitter, extname) => {
fs.readFile("./json/mime.json", (err, data) => {
if (err) throw err;
EventEmitter.emit("mime_type", JSON.parse(data.toString())[extname]);
});
};
事件驱动的版本(还有一个回调函数的版本,很类似的写法)