灏天阁

NODEJS[24]:http模块_搭建静态资源服务

· Yin灏

目录结构

|-- page #资源文件夹
    |-- css
    |-- js
    |-- images
    |-- index.html
|-- server.js

server.js

const http = require("http");
const fs = require("fs");
const server = http.createServer((request, response) => {
  let { pathname } = new URL(request.url, "http://127.0.0.1");
  // 拼接文件路径
  let filePath = __dirname + "/page" + pathname;
  // 读取文件
  fs.readFile(filePath, (err, data) => {
    if (err) {
      response.statusCode = 500;
      response.end("文件读取失败");
      return;
    }
    response.end(data);
  });
});
server.listen(9000, () => {
  cons.log("服务器已经启动了...");
});

- Book Lists -