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

相关推荐
tokepson2 小时前
Mysql下载部署方法备份(Windows/Linux)
linux·服务器·windows·mysql
nbsaas-boot4 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
zz_nj5 小时前
工作的环境
linux·运维·服务器
willhuo6 小时前
基于xray的匿名、授权、IP白名单代理访问研究
服务器·网络·tcp/ip
南烟斋..7 小时前
GDB调试核心指南
linux·服务器
掘根9 小时前
【仿Muduo库项目】HTTP模块3——HttpContext子模块
网络·网络协议·http
瓦尔登湖懒羊羊9 小时前
到底能不能把HTTP1.0讲明白了
http
像风一样自由9 小时前
android native 中的函数动态注册方式总结
android·java·服务器·安卓逆向分析·native函数动态注册·.so文件分析
小李独爱秋10 小时前
计算机网络经典问题透视:TLS协议工作过程全景解析
运维·服务器·开发语言·网络协议·计算机网络·php
阿甘正赚.10 小时前
Linux初学
linux·运维·服务器