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

相关推荐
开发者小天5 小时前
python中For Loop的用法
java·服务器·python
绾樘5 小时前
RHCE--基于Nginx的Web服务器配置
运维·服务器·nginx
生活很暖很治愈5 小时前
Linux基础开发工具
linux·服务器·git·vim
步步为营DotNet8 小时前
深度剖析.NET中IHostedService:后台服务管理的关键组件
服务器·网络·.net
Ghost Face...10 小时前
i386 CPU页式存储管理深度解析
java·linux·服务器
DARLING Zero two♡10 小时前
【计算机网络】简学深悟启示录:http
网络协议·计算机网络·http
Yu_Lijing10 小时前
《图解HTTP》笔记与读后感(上)
网络·笔记·网络协议·http
czy878747511 小时前
connect() 的阻塞特性取决于它所关联的 socket 是否被设置为非阻塞模式,connect() 会等待 TCP 三次握手的超时时间
服务器·网络·tcp/ip
geshifei11 小时前
Sched ext回调2——enable(linux 6.15.7)
linux·运维·服务器
傻啦嘿哟12 小时前
Python批量重命名照片并按拍摄日期归类:从原理到实践
linux·运维·服务器