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

相关推荐
青草地溪水旁24 分钟前
http response的工作流程详细解析
网络协议·http·应答
当归102426 分钟前
SQL Server死锁排查实战指南
java·服务器·网络
凉伊38 分钟前
HTTP 协议:从原理到应用的深度剖析
网络·网络协议·http
qinyia1 小时前
用 Wisdom SSH 轻松实现服务器自动化任务调度
服务器·自动化·ssh
bug攻城狮1 小时前
彻底禁用 CentOS 7.9 中 vi/vim 的滴滴声
linux·运维·服务器·centos·vim
艾小码1 小时前
手把手教你实现一个EventEmitter,彻底告别复杂事件管理!
前端·javascript·node.js
前端小哲3 小时前
MCP从入门到实战
node.js·ai编程
dasseinzumtode4 小时前
nestJS 使用ExcelJS 实现数据的excel导出功能
前端·后端·node.js
Sweety丶╮7944 小时前
【Ansible】实施 Ansible Playbook知识点
服务器·云原生·ansible
optiz5 小时前
细菌基因组genome二代测序数据分析
linux·运维·服务器