灏天阁

NODEJS[23]:http模块_实现网页引入外部资源

· Yin灏

文件结构

|-- demo
    |-- index.css
    |-- index.js
    |-- index.html
    |-- main.js #主文件

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./index.css" />
  </head>
  <body>
    <script src="./index.js"></script>
  </body>
</html>

main.js

const http = require("http");
const fs = require("fs");
const server = http.createServer((request, response) => {
  // 获取请求 url 的路径
  let { pathname } = new URL(request.url, "http://127.0.0.1");
  if (pathname === "/") {
    let html = fs.readFileSync(__dirname + "/index.html");
    // .end 可以处理 Buffer
    response.end(html);
  } else if (pathname === "/index.css") {
    let css = fs.readFileSync(__dirname + "/index.css");
    response.end(css);
  } else if (pathname === "/index.js") {
    let js = fs.readFileSync(__dirname + "/index.js");
    response.end(js);
  } else {
    response.statusCode = 404;
    response.end("<h1>404 Not Found</h1>");
  }
});
server.listen(9000, () => {
  cons.log("服务器已经启动了...");
});

- Book Lists -