极简 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 -- 表单元素1
HTML 表单用于搜集不同类型的用户输入. 一.<form> 标签 <form> 标签用于为用户输入创建 HTML 表单. 表单能够包含 input 元素,比如文本字段.复选框 ...
- ssh 远程执行命令 nohup 无效问题
昨夜1:00多准备睡觉了,突然一哥们咨询了我一个问题. 他A机器上远程执行B机器(ssh user@ip "command")上的脚本,B上的服务并没有起来. 看了下截图,脚本确实 ...
- Java 内存模型(Java Memory Model,JMM)
基本概念 JMM 本身是一种抽象的概念并不是真实存在,它描述的是一组规范,通过这组规范定义了程序的访问方式 JMM 同步规定 线程解锁前,必须把共享变量的值刷新回主内存 线程加锁前,必须读取主内存的最 ...
- php bypass disable function
前言 最近开学,事太多了,好久没更新了,然后稍微闲一点一直在弄这个php bypass disable function,一开始自己的电脑win10安装蚁剑的插件,一直报错.怀疑是必须linux环境. ...
- 阿里云恶意软件检测比赛-第三周-TextCNN
LSTM初试遇到障碍,使用较熟悉的TextCNN. 1.基础知识: Embedding:将词的十进制表示做向量化 起到降维增维的作用 嵌入维度数量(New Embedding维度)的一般经验法则: e ...
- Hibernate4.3基础知识2
一.数据库的隔离级别 脏读 不可重复读 幻读 Read uncommited Y Y Y Read commited N Y Y Repeatable read N N Y Serializabl ...
- Python-临时文件文件模块-tempfile
案例: 某项目中,从传感器中获得采集数据,每收集到1G的数据后做是数据分析,最终只保留数据分析的结果,收集到的数据放在内存中,将会消耗大量内存,我们希望把这些数据放到一个临时的文件中 临时文件不能命名 ...
- sipp3.6对freeswitch进行压力测试
一.安装sipp 1.下载地址: https://github-production-release-asset-2e65be.s3.amazonaws.com/13161657/99df6100-9 ...
- LPCTSTR类型和字符串
转载: 1.https://blog.csdn.net/Joker_mw/article/details/79127790 2.https://blog.csdn.net/shelleyhuhu/ar ...
- matlab中wvtool
参考:https://ww2.mathworks.cn/help/signal/ref/wvtool.html?searchHighlight=wvtool&s_tid=doc_srchtit ...