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

相关推荐
dldw77718 小时前
IE无法正常登录windows2000server的FTP服务器
运维·服务器·网络
我是伪码农19 小时前
外卖餐具智能推荐
linux·服务器·前端
汤愈韬19 小时前
下一代防火墙通用原理
运维·服务器·网络·security
IMPYLH19 小时前
Linux 的 od 命令
linux·运维·服务器·bash
数据雕塑家21 小时前
Linux下大文件切割与合并实战:解决FAT32文件系统传输限制
linux·运维·服务器
IMPYLH21 小时前
Linux 的 nice 命令
linux·运维·服务器·bash
yleihj1 天前
vCenter计算机SSL证书续期
服务器·网络协议·ssl
航Hang*1 天前
Windows Server 配置与管理——第12章:配置数字证书服务器
运维·服务器·windows
lifewange1 天前
https和http有什么区别
网络协议·http·https
爱学习的小囧1 天前
vSphere Supervisor 服务配置指南:自签名容器注册表使用教程
服务器·网络·esxi·虚拟化·vcf