本文共 2441 字,大约阅读时间需要 8 分钟。
搭建一个高效的静态资源服务器,可以通过Node.js实现根据文件扩展名自动设置响应头的功能。以下将详细介绍实现方法及其应用场景。
Web服务器是现代网站开发的核心基础设施之一。通过Node.js搭建静态资源服务器,可以高效地管理网站资源文件,同时根据不同文件类型自动设置响应头,提升开发效率。
文件扩展名是区分不同文件类型的重要依据。通过将文件扩展名与对应的MIME类型建立映射关系,可以实现自动设置响应头的功能。
服务器逻辑主要包含以下步骤:
以下是完整的服务器代码示例:
const http = require('http');const fs = require('fs');const path = require('path');const url = require('url');const common = require('./module/common');http.createServer((req, res) => { const pathname = url.parse(req.url).pathname; // 设置根路径为index.html const root = pathname === '/' ? '/index.html' : pathname; // 获取文件扩展名 const extname = path.extname(root); // 读取文件内容 if (root !== '/favicon.ico') { fs.readFile(`./static${root}`, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('404 Page Not Found'); } else { const mime = common.getFileMime(extname); res.writeHead(200, { 'Content-Type': `${mime}; charset=utf-8` }); res.end(data); } }); } else { fs.readFile('./static/favicon.ico', (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('404 Page Not Found'); } else { res.writeHead(200, { 'Content-Type': 'image/x-icon' }); res.end(data); } }); }}).listen(3000);console.log('Server running at http://127.0.0.1:3000/'); 路径处理:通过url.parse解析请求路径,确保根路径指向index.html,以便于单页应用访问。
扩展名获取:使用path.extname获取文件扩展名,作为设置响应头的依据。
文件读取:根据路径读取对应文件。如非favicon.ico文件,直接返回文件内容。
MIME类型映射:通过公共方法getFileMime查找扩展名对应的MIME类型,并设置响应头。
为了实现扩展名与MIME类型的映射,需要预先准备一个mime.json文件。以下是示例内容:
{ ".323": "text/h323", ".3gp": "video/3gpp", ".aab": "application/x-authoware-bin", // ... 其他扩展名对应关系 ".zip": "application/zip", ".htm": "text/html", ".html": "text/html", ".css": "text/css", ".js": "application/x-javascript"} 项目布局:
app.js文件。static目录,存放静态资源文件。module和data目录,分别存放公共方法和MIME类型映射文件。终端运行:
node app.js
服务器将运行在http://127.0.0.1:3000/。
访问测试:
http://localhost:3000/http://localhost:3000/index.htmlhttp://localhost:3000/static.zip通过上述方法,可以轻松搭建一个功能高效的静态资源服务器。服务器根据文件扩展名自动设置响应头,使资源加载更高效。这种配置方式适用于静态网站、单页应用以及需要灵活资源管理的场景。
转载地址:http://atjfk.baihongyu.com/