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

相关推荐
卷Java7 小时前
Linux服务器Docker部署OpenClaw:腾讯云/阿里云/VPS安装避坑指南
linux·运维·服务器
原来是猿9 小时前
Linux-【动静态库】
linux·运维·服务器
深圳市恒讯科技10 小时前
云服务器怎么选?从CPU、内存到IOPS的零基础选型手册
运维·服务器
艾莉丝努力练剑11 小时前
【脉脉】AI创作者崛起:掌握核心工具,在AMA互动中共同成长
运维·服务器·c++·人工智能·安全·企业·脉脉
chinesegf12 小时前
DNS 验证验证SSL证书
linux·服务器·网络
LXY_BUAA13 小时前
《嵌入式操作系统》_高级字符设备驱动_20260316
linux·运维·服务器·驱动开发
IMPYLH15 小时前
Linux 的 chmod 命令
linux·运维·服务器
艾莉丝努力练剑15 小时前
【MYSQL】MYSQL学习的一大重点:数据库基础
linux·运维·服务器·数据库·c++·学习·mysql
雷帝木木15 小时前
Flutter for OpenHarmony:Flutter 三方库 cbor 构建 IoT 设备的极致压缩防窃协议(基于标准二进制 JSON 表达格式)
网络·物联网·flutter·http·json·harmonyos·鸿蒙
ht巷子16 小时前
boost.asio网络学习:Http Server
网络·c++·http