Create a new 62 folder and add three files inside
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>凯小默的博客</title>
<link rel="stylesheet" href="/62/index.css">
</head>
<body>
<h1>凯小默的博客</h1>
<script src="/62/index.js"></script>
</body>
</html>
index.js
console.log("kaimo 666");
index.css
body {
background-color: seagreen;
}
Note: The processing request is single-threaded (the code should be asynchronous as much as possible, otherwise the main thread will be blocked)
For example: the following writing method will block, accessing first http://localhost:3000/sum
and then accessing http://localhost:3000
will cause the access to keep going, and you need to wait for the sum to be processed
if (pathname === "/sum") {
let sum = 0;
for (let i = 0; i < 10000000000; i++) {
sum += i;
}
res.end(sum + "");
} else {
res.end("ok");
}
It is necessary to determine whether the file exists first fs.stat
. If you directly access http://localhost:3000/62
the path, you can directly access itindex.html
const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
// 访问链接 http://localhost:3000/62/index.html
const server = http.createServer((req, res) => {
let {
pathname } = url.parse(req.url, true);
console.log(pathname); // /62/index.html 有路径 `/` 直接 join 拼接
const filePath = path.join(__dirname, pathname);
console.log(filePath);
fs.stat(filePath, (err, statObj) => {
if (err) {
res.end("not found");
} else {
if (statObj.isFile()) {
fs.createReadStream(filePath).pipe(res);
} else {
let file = path.join(filePath, "index.html");
fs.stat(file, (err, statObj) => {
if (err) {
res.end("not found");
} else {
fs.createReadStream(file).pipe(res);
}
});
}
}
});
});
server.listen(3000);
The overall function is not completed
const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
class Server {
handleRequest(res, req) {
console.log("handleRequest--->", this);
// 不使用 bind,就需要 return 一个函数
// return () => {
// console.log("handleRequest--->2", this);
// };
}
start(...args) {
// bind 原理就是产生一个新的函数
const server = http.createServer(this.handleRequest.bind(this));
server.listen(...args);
}
}
let server = new Server();
server.start(3000, () => {
console.log("server run 3000");
});