啊?Node.js 还能这样?

309 阅读3分钟

使用 Node.js 构建一个简单的 HTTP 静态文件服务器

Node.js 其实就是一个让 JavaScript 可以在电脑上跑起来的环境,它用的是 Google Chrome 里面那个超快的 V8 引擎。正因为这个特性,Node.js 非常适合用来做后端开发,尤其是那些需要高性能、容易扩展的应用。它内置了很多实用的模块,比如 http(用来创建服务器)、fs(操作文件)和 path(处理路径),这些都让开发者能更轻松地写出功能强大的服务。

这篇文章呢,就是带你用 Node.js 搭建一个简单的静态文件服务器。说白了,就是让你输入一个网址,服务器就能根据地址返回对应的网页文件,比如 HTML 页面、CSS 样式表或者 JS 脚本。整个过程不复杂,但能帮你理解 Node.js 是怎么处理 HTTP 请求的。

一、Node.js 模块化方案简介

为什么需要模块化?

  • 更好的组织代码
  • 提高复用性
  • 避免命名冲突
  • 支持异步加载模块(浏览器端)

已知的node.js中有两大主流模块化方案:

  1. CommonJS(require)
    这是 Node.js 早期使用的模块化规范,通过 require() 来引入模块,使用 module.exports 导出内容。
  2. ES6 Modules(import / export)
    ES6 引入了更现代化的模块化语法,使用 importexport 关键字。虽然现代项目中越来越多地采用这种写法,但传统的 Node.js 应用仍大量使用 CommonJS。

二、CommonJs 核心模块介绍

以下是我们在构建静态服务器时会用到的几个 Node.js 核心模块:

  1. http:这是用来创建http服务器。
  2. fs:(file system)是用来读取和写入系统中的文件。
  3. path:path是使得路径模块化是用来拼接和处理文件路径避免跨平台问题。

三、ES6 Modules 核心模块介绍

  1. export导出模块内容:
export function add(a, b) { return a + b; } export const PI = 3.14;

2.import导入模块内容:

import { add, PI } from './math.js'; console.log(add(2, 3)); // 5 console.log(PI); // 3.14

四 、搭建静态文件服务器

前几步骤我们已经知道了两大模块化的核心模块,接下来我们来搭建静态文件服务器

1.引入核心模块

const http = require('http');
const fs = require('fs'); // file system 
const path = require('path'); // 路径模块

2.创建HTTP服务器

const server = http.createServer((req, res) => {

http 基于请求响应的协议 路由 Method + url 定位了服务器端的资源

  • req: request 请求对象,包含客户端发来的信息(如 URL、方法等)
  • res: response 响应对象,用于向客户端发送数据

3.路由判断与响应内容

a.首页请求 / 或 /index.html

if (req.method == 'GET' && 
(req.url == '/' || req.url == '/index.html')) {

fs.readFile(
path.join(__dirname,'public', 'index.html'),
(err, content) => {
if (err) { res.writeHead(500); // 5XX 服务器错误
res.end('Server error');
return;
} 
res.writeHead(200, { 'Content-Type': 'text/html' }) res.end(content);
})
}
  • 如果用户访问根路径 / 或 /index.html
  • 使用 fs.readFile() 从 public/index.html 读取文件内容
  • 出现错误时返回 500 错误码和提示
  • 成功则设置响应头 Content-Type: text/html 并返回文件内容

b.CSS 请求 /style.css

if (req.method == 'GET' && req.url == '/style.css') { 
fs.readFile(
path.join(__dirname, 'public', 'style.css'), 
(err, content) => {
if (err) {
res.writeHead(500);
res.end('Server error');
return;
} 
res.writeHead(200, { 'Content-Type': 'text/css' }) res.end(content);
}
); 
return;
}
  • 当用户访问 /style.css 时,读取并返回 CSS 文件
  • 设置正确的 MIME 类型为 text/css

c.JS 请求 /server.js

if (req.method == 'GET' && req.url == '/server.js') { fs.readFile(
path.join(__dirname, 'public', 'server.js'), 
(err, content) => {
if (err) { 
res.writeHead(500); 
res.end('Server error');
return;
} 
res.writeHead(200, { 'Content-Type': 'text/javascript'})
res.end(content);
} ); 
return;
}
  • 访问 /server.js 时,读取并返回 JS 文件
  • MIME 类型为 text/javascript

五、运行服务器

  1. 在终端进入项目目录。

  2. 执行命令启动服务器:

    node server.js
    
  3. 打开浏览器访问:http://localhost:8080

你将看到 index.html 页面被正确加载,并且页面引用的 CSS 和 JS 文件也能正常加载。

六、总结

1.端口选择:一般选择1000出头的端口,不要选择一些特殊的端口例如:如 80,443,3306 这会导致连接出错

2.node版本:一般来说node默认不支持es6 的模块化但是在node最新版本可能支持es6模块化,在平时如果用的是es6模块化文件后缀要改成.mjs