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

相关推荐
前端张三14 分钟前
Mac 电脑pink 后端ip地址进行本地联调
服务器·tcp/ip·macos
余生H14 分钟前
前端的全栈混合之路Meteor篇:关于前后端分离及与各框架的对比
前端·javascript·node.js·全栈
第六五22 分钟前
ubuntu命令行连接wifi
服务器·ubuntu
CXDNW25 分钟前
【网络篇】计算机网络——应用层详述(笔记)
服务器·笔记·计算机网络·http·web·cdn·dns
zeruns80238 分钟前
如何搭建自己的域名邮箱服务器?Poste.io邮箱服务器搭建教程,Linux+Docker搭建邮件服务器的教程
linux·运维·服务器·docker·网站
北城青44 分钟前
WebRTC Connection Negotiate解决
运维·服务器·webrtc
Hugo_McQueen1 小时前
pWnos1.0 靶机渗透 (Perl CGI 的反弹 shell 利用)
linux·服务器·网络安全
Ink1 小时前
从底层看 path.resolve 实现
前端·node.js
XY.散人1 小时前
初识Linux · 文件(1)
linux·运维·服务器
秋夫人2 小时前
http cache-control
网络·网络协议·http