Node.js 自带的 http 模块来实现一个简单的本地服务器

1.创建一个 server.js 文件:

复制代码
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // 获取请求的文件路径
  const filePath = path.join(__dirname, 'dist', req.url);
  
  // 读取文件内容并返回给客户端
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('Not Found');
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    }
  });
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server is running at http://127.0.0.1:${port}`);
});

node server.js

相关推荐
RoyLin1 天前
TypeScript设计模式:原型模式
前端·后端·node.js
RoyLin1 天前
TypeScript设计模式:单例模式
前端·后端·node.js
RoyLin1 天前
TypeScript设计模式:工厂方法模式
前端·后端·node.js
RoyLin1 天前
TypeScript设计模式:模板方法模式
前端·后端·node.js
moonless02221 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
RoyLin2 天前
TypeScript设计模式:适配器模式
前端·后端·node.js
RoyLin2 天前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
東雪蓮☆2 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
乌萨奇也要立志学C++2 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器