极简 Node.js 入门 - 5.3 静态资源服务器
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node
在创建 HTTP 服务器实现了一个最简单的静态资源服务器,可以对代码进行写改造,增加文件夹预览功能,暴露出一些配置,变成一个可定制的静态资源服务器模块
模块化
可定制的静态资源服务器理想的使用方式应该是这样的
const StaticServer = require('YOUR_STATIC_SERVER_FILE_PATH');
const staticServer = new StaticServer({
port: 9527,
root: '/public',
});
staticServer.start();
staticServer.close();
这样的使用方式就要求代码实现模块化,Node.js 实现一个模块非常简单
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const defaultConf = require('./config');
class StaticServer {
constructor(options = {}) {
this.config = Object.assign(defaultConf, options);
}
start() {
const { port, root } = this.config;
this.server = http.createServer((req, res) => {
const { url, method } = req;
if (method !== 'GET') {
res.writeHead(404, {
'content-type': 'text/html',
});
res.end('请使用 GET 方法访问文件!');
return false;
}
const filePath = path.join(root, url);
fs.access(filePath, fs.constants.R_OK, err => {
if (err) {
res.writeHead(404, {
'content-type': 'text/html',
});
res.end('文件不存在!');
} else {
res.writeHead(200, {
'content-type': mime.contentType(path.extname(url)),
});
fs.createReadStream(filePath).pipe(res);
}
});
}).listen(port, () => {
console.log(`Static server started at port ${port}`);
});
}
stop() {
this.server.close(() => {
console.log(`Static server closed.`);
});
}
}
module.exports = StaticServer;
完整代码:https://github.com/Samaritan89/static-server/tree/v1
执行 npm run test 可以测试

支持文件夹预览
当访问的路径是文件夹的时候程序会报错
Error: EISDIR: illegal operation on a directory, read
Emitted 'error' event on ReadStream instance at:
at internal/fs/streams.js:217:14
at FSReqCallback.wrapper [as oncomplete] (fs.js:524:5) {
errno: -21,
code: 'EISDIR',
syscall: 'read'
}
因为 fs.createReadStream 尝试读取文件夹,需要兼容下访问路径是文件夹的时候,返回一个目录页,也就是在 fs.access 之后判断文件类型
fs.access(filePath, fs.constants.R_OK, err => {
if (err) {
res.writeHead(404, {
'content-type': 'text/html',
});
res.end('文件不存在!');
} else {
const stats = fs.statSync(filePath);
const list = [];
if (stats.isDirectory()) {
// 如果是文件夹则遍历文件夹,生成改文件夹内的文件树
// 遍历文件内容,生成 html
} else {
res.writeHead(200, {
'content-type': mime.contentType(path.extname(url)),
});
fs.createReadStream(filePath).pipe(res);
}
}
});
遍历生成 html 部分需要用到 文件夹操作 章节介绍的知识,为了方便生成 HTML,demo 使用了 Handlebar 模板引擎,主要逻辑
if (stats.isDirectory()) {
// 如果是文件夹则遍历文件夹,生成改文件夹内的文件树
const dir = fs.opendirSync(filePath);
let dirent = dir.readSync();
while (dirent) {
list.push({
name: dirent.name,
path: path.join(url, dirent.name),
type: dirent.isDirectory() ? 'folder' : 'file',
});
dirent = dir.readSync();
}
dir.close();
res.writeHead(200, {
'content-type': 'text/html',
});
// 对文件顺序重排,文件夹在文件前面,相同类型按字母排序,不区分大小写
list.sort((x, y) => {
if (x.type > y.type) {
// 'folder' > 'file', 返回 -1,folder 在 file 之前
return -1;
} else if (x.type == y.type) {
return compare(x.name.toLowerCase(), y.name.toLowerCase());
} else {
return 1;
}
});
// 使用 handlebars 模板引擎,生成目录页面 html
const html = template({ list });
res.end(html);
}
通过 git 代码修改记录可以清晰看到本次的变更:https://github.com/Samaritan89/static-server/commit/5565788dc317f29372f6e67e6fd55ec92323d0ea
同样在项目根目录执行 npm run test ,使用浏览器访问 127.0.0.1:9527 可以看到目录文件的展示
完整代码:https://github.com/Samaritan89/static-server/tree/v2
极简 Node.js 入门 - 5.3 静态资源服务器的更多相关文章
- 极简 Node.js 入门 - 5.1 创建 HTTP 服务器
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - Node.js 是什么、性能有优势?
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 1.2 模块系统
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 1.3 调试
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 1.4 NPM & package.json
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 2.1 Path
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 2.2 事件
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 2.3 process
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- 极简 Node.js 入门 - 2.4 定时器
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
随机推荐
- HTML -- 表单元素2
(1)<select>元素(下拉列表) <html> <body> <!-- 表单处理程序在action属性中指定 --> <form actio ...
- Shell编程(5)
文本处理三剑客 在 Shell 下使用这些正则表达式处理文本最多的命令有下面几个工具: 命令 描述 grep 默认不支持扩展表达式,加-E ...
- day53:django:URL别名/反向解析&URL分发&命名空间&ORM多表操作修改/查询
目录 1.URL别名&反向解析 2.URL分发&命名空间 3.ORM多表操作-修改 4.ORM多表操作-查询 4.1 基于对象的跨表查询 4.2 基于双下划线的跨表查询 4.3 聚合查 ...
- 集群数据ID生成之美团叶子生成
转自https://tech.meituan.com/2017/04/21/mt-leaf.html 在复杂分布式系统中,往往需要对大量的数据和消息进行唯一标识.如在美团点评的金融.支付.餐饮.酒店. ...
- archaius(2) 配置源
上一节讲到,archaius实现动态配置的核心就是定时去配置中心拉去配置内容,接下来几接就来看一下archaius内部具体是如何实现的. 首先我们来了解一下配置源,什么是配置源呢,archaius内部 ...
- 3.Scala语法01 - 基础语法
- 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统一 | 前言
教程预览 01 | 前言 02 | 简单的分库分表设计 03 | 控制反转搭配简单业务 04 | 强化设计方案 05 | 完善业务自动创建数据库 06 | 最终篇-通过AOP自动连接数据库-完成日志业 ...
- Java随谈(二)对空指针异常的碎碎念
本文适合对 Java 空指针痛彻心扉的人阅读,推荐阅读时间25分钟. 若有一些Java8 函数式编程的基础可以当成对基础知识的巩固. 一.万恶的null 今天,我们简单谈谈null的问题.因为null ...
- windows提权之mimikatz
mimikatz privilege::debug #提权命令 sekurlsa::logonPasswords #抓取密码 winmine::infos #扫雷作弊 lsadump::lsa /pa ...
- python中获取中位数
普通方法: 对列表进行排序,然后根据长度为奇数或者偶数的不同情况计算中位数 def huahua(x): length = len(x) print(length) x.sort() print(x) ...