新建 62 文件夹,里面添加三个文件
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; }
注意:处理请求是单线程(代码尽量采用异步,否则会阻塞主线程)
比如:下面的写法就会阻塞,先访问 http://localhost:3000/sum
再去访问 http://localhost:3000
就会导致访问时一直转,需要等待 sum 处理完毕
if (pathname === "/sum") { let sum = 0; for (let i = 0; i < 10000000000; i++) { sum += i; } res.end(sum + ""); } else { res.end("ok"); }
需要先判断文件是否存在 fs.stat
,如果直接访问 http://localhost:3000/62
路径,实现可以直接访问到 index.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);
未完成整体功能
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"); });