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

相关推荐
arronKler1 天前
大数据量高并发的数据库优化
服务器·数据库·oracle
星辰_mya1 天前
OSI 七层模型之“跨国诈骗集团”深度讲解
运维·服务器·后端·面试·架构师
iNgs IMAC1 天前
如何在Windows系统上安装和配置Node.js及Node版本管理器(nvm)
windows·node.js
实心儿儿1 天前
Linux —— 基础IO - 文件描述符
linux·运维·服务器
clear sky .1 天前
[linux]视频实时推流项目
linux·服务器·音视频
RisunJan1 天前
Linux命令-nisdomainname(显示或设置系统的 NIS(Network Information Service)域名)
linux·运维·服务器
Wy_编程1 天前
nginx测试
服务器·nginx
小此方1 天前
Re:Linux系统篇(四)指令篇 · 三:两套打包压缩重要指令方法+剩余指令收尾
linux·运维·服务器
~ rainbow~1 天前
前端转型全栈(六)——深入浅出:文件上传的原理与进阶
前端·http·文件上传
小宏运维有点菜1 天前
服务器 BMC 管理 IP
服务器·tcp/ip·centos