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

相关推荐
Web极客码3 小时前
如何在Ubuntu服务器上安装和配置BIND9
服务器·数据库·ubuntu
吳所畏惧3 小时前
Linux环境/麒麟V10SP3下离线安装Redis、修改默认密码并设置Redis开机自启动
linux·运维·服务器·redis·中间件·架构·ssh
西***63474 小时前
全兼容・高安全:KVM 一站式服务器远程监控与管理指南
服务器
萧曵 丶5 小时前
Linux 业务场景常用命令详解
linux·运维·服务器
youxiao_906 小时前
kubernetes 概念与安装(一)
linux·运维·服务器
凡梦千华6 小时前
logrotate日志切割
linux·运维·服务器
在西安放羊的牛油果7 小时前
浅谈 import.meta.env 和 process.env 的区别
前端·vue.js·node.js
拜托啦!狮子7 小时前
安装和使用Homer(linux)
linux·运维·服务器
鹏北海7 小时前
从弹窗变胖到 npm 依赖管理:一次完整的问题排查记录
前端·npm·node.js
liulilittle8 小时前
XDP VNP虚拟以太网关(章节:一)
linux·服务器·开发语言·网络·c++·通信·xdp