Node.js 返回静态资源
在使用 Node.js 构建服务器时,返回静态资源(如 HTML、CSS、JavaScript 文件、图片等)是一个常见的需求。最简单的解决方案是使用内置的 fs
模块来读取文件并将其作为响应发送给客户端,或者使用第三方库如 express
来简化这个过程。
几种实现方法,并提供完整的代码示例。
方法一:使用原生 fs 模块
Node.js 提供了 fs
模块,可以用来读取文件系统中的文件。我们可以结合 http
模块创建一个简单的 HTTP 服务器,手动处理静态资源的返回。
实现步骤:
- 使用
fs.readFile
方法读取文件内容。 - 根据文件类型设置正确的 MIME 类型(如
text/html
,application/javascript
等)。 - 将文件内容通过 HTTP 响应返回给客户端。
示例代码:
javascript
const http = require('http');
const fs = require('fs');
const path = require('path');</p>
<p>// 创建服务器
const server = http.createServer((req, res) => {
// 解析请求路径
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html'; // 默认返回 index.html
}</p>
<pre><code>// 设置文件扩展名和 MIME 类型映射
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff'
};
const contentType = mimeTypes[extname] || 'application/octet-stream';
// 读取文件并返回
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
// 文件不存在,返回 404
fs.readFile('./404.html', (err, content) => {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
});
} else {
// 其他错误
res.writeHead(500);
res.end('Server Error: ' + err.code + 'n');
}
} else {
// 正常返回文件
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// 监听端口
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
方法二:使用 Express 框架
Express 是一个流行的 Node.js Web 框架,提供了许多方便的功能,包括内置的静态文件服务功能。使用 Express 可以极大地简化代码量。
实现步骤:
- 安装 Express:
npm install express
- 使用
express.static
中间件指定静态资源目录。
示例代码:
javascript
const express = require('express');
const path = require('path');</p>
<p>const app = express();</p>
<p>// 设置静态资源目录
app.use(express.static(path.join(__dirname, 'public')));</p>
<p>// 启动服务器
app.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
在这个例子中,public
文件夹中的所有文件都会被自动处理为静态资源。例如,如果访问 http://localhost:3000/style.css
,Express 会从 public
文件夹中查找 style.css
并返回。
方法三:使用第三方库 serve-static
如果你不想使用 Express,但仍然希望有一个简单的方式来处理静态文件,可以使用 serve-static
库。这是一个独立的中间件库,专门用于提供静态文件服务。
实现步骤:
- 安装
serve-static
和finalhandler
:npm install serve-static finalhandler
- 使用
serve-static
处理静态文件请求。
示例代码:
javascript
const http = require('http');
const serveStatic = require('serve-static');
const finalhandler = require('finalhandler');</p>
<p>// 创建 serve-static 实例
const serve = serveStatic('public', { index: ['index.html'] });</p>
<p>// 创建服务器
const server = http.createServer((req, res) => {
serve(req, res, finalhandler(req, res));
});</p>
<p>// 监听端口
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
在这个例子中,serve-static
负责处理静态文件请求,而 finalhandler
则用于处理请求链结束后的清理工作。
以上三种不同的方式来让 Node.js 返回静态资源:
1. 原生 fs 模块:适合对性能有要求的场景,但需要手动处理文件类型和错误。
2. Express 框架:简单易用,适合快速开发项目。
3. serve-static 库:轻量级且灵活,适合不使用框架的场景。
根据实际需求选择合适的方法即可!