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

相关推荐
西西学代码几秒前
Flutter---简单画板应用
服务器·数据库·flutter
一只程序熊几秒前
uniappx richtext img 图片无法显示
linux·服务器·数据库
女王大人万岁1 分钟前
Golang实战Eclipse Paho MQTT库:MQTT通信全解析
服务器·开发语言·后端·golang
Stewie1213810 分钟前
企业高性能web服务器——Nginx
服务器·前端·nginx
林开落L6 小时前
解决云服务器内存不足:2 分钟搞定 Ubuntu swap 交换区配置(新手友好版)
运维·服务器·ubuntu·swap交换区
成为你的宁宁8 小时前
Jenkins 自动化部署前后端分离若依项目全攻略:涵盖环境配置、Maven/Node.js 工具安装、GitLab 项目协同,及前后端构建、服务器推送与代码更新验证全步骤
node.js·自动化·gitlab·jenkins·maven
2301_8059629311 小时前
arduino IDE如何设置代理
运维·服务器
huaweichenai12 小时前
Linux安装http-server并部署html静态站点
linux·运维·服务器
北冥湖畔的燕雀13 小时前
Linux权限与Vim,gcc以及make/makefile操作全解析
linux·运维·服务器
折七14 小时前
NestJS 用了两年,我换了这个
typescript·node.js·nestjs