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

相关推荐
竹林81827 分钟前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js
w-w0w-w33 分钟前
Unix网络编程
服务器·网络·unix
肠胃炎2 小时前
挂载方式部署项目
服务器·前端·nginx
mldlds2 小时前
windows手动配置IP地址与DNS服务器以及netsh端口转发
服务器·windows·tcp/ip
一直都在5723 小时前
深入理解 synchronized:到底锁的是谁?
运维·服务器
RisunJan3 小时前
Linux命令-mkbootdisk(可建立目前系统的启动盘)
linux·运维·服务器
朽棘不雕4 小时前
Linux工具(上)
linux·运维·服务器
daad7774 小时前
bitcoin HD钱包示例 真实使命7
运维·服务器
Zero-Talent4 小时前
TCP/IP协议
运维·服务器·网络
Du_chong_huan4 小时前
1.7 计算机网络和因特网的历史 | 《计算机网络:自顶向下方法》精读版
运维·服务器·网络