如何使用Node实现搭建静态资源服务器?
- 内容介绍
- 文章标签
- 相关推荐
本文共计2798个文字,预计阅读时间需要12分钟。
使用 Node 的内置模块,创建一个可访问目录的静态资源服务器,支持 fs 文件读取,资源压缩与缓存等。一、创建 HTTP Server 服务器 Node 的 http 模块提供 HTTP 服务器和客户端功能,可以方便地创建 HTTP 服务器和客户端。以下是一个简单的示例代码:
javascriptconst http=require('http');const fs=require('fs');const path=require('path');
const server=http.createServer((req, res)=> { const filePath=path.join(__dirname, 'public', req.url); fs.readFile(filePath, (err, data)=> { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('File not found'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } });});
server.listen(3000, ()=> { console.log('Server running on port 3000');});
这段代码创建了一个 HTTP 服务器,监听 3000 端口。当接收到请求时,它会读取 `public` 目录下的文件,并将文件内容作为响应返回。如果文件不存在,则返回 404 错误。
二、支持 fs 文件读取
在上面的代码中,我们已经使用了 `fs.readFile` 方法来读取文件。这个方法可以异步地读取文件内容,并返回一个 Buffer 对象。
本文共计2798个文字,预计阅读时间需要12分钟。
使用 Node 的内置模块,创建一个可访问目录的静态资源服务器,支持 fs 文件读取,资源压缩与缓存等。一、创建 HTTP Server 服务器 Node 的 http 模块提供 HTTP 服务器和客户端功能,可以方便地创建 HTTP 服务器和客户端。以下是一个简单的示例代码:
javascriptconst http=require('http');const fs=require('fs');const path=require('path');
const server=http.createServer((req, res)=> { const filePath=path.join(__dirname, 'public', req.url); fs.readFile(filePath, (err, data)=> { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('File not found'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } });});
server.listen(3000, ()=> { console.log('Server running on port 3000');});
这段代码创建了一个 HTTP 服务器,监听 3000 端口。当接收到请求时,它会读取 `public` 目录下的文件,并将文件内容作为响应返回。如果文件不存在,则返回 404 错误。
二、支持 fs 文件读取
在上面的代码中,我们已经使用了 `fs.readFile` 方法来读取文件。这个方法可以异步地读取文件内容,并返回一个 Buffer 对象。

