极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node

本文更佳阅读体验:https://www.yuque.com/sunluyong/node/static-server

创建 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 静态资源服务器的更多相关文章

  1. 极简 Node.js 入门 - 5.1 创建 HTTP 服务器

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  2. 极简 Node.js 入门 - Node.js 是什么、性能有优势?

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  3. 极简 Node.js 入门 - 1.2 模块系统

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  4. 极简 Node.js 入门 - 1.3 调试

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  5. 极简 Node.js 入门 - 1.4 NPM & package.json

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  6. 极简 Node.js 入门 - 2.1 Path

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  7. 极简 Node.js 入门 - 2.2 事件

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  8. 极简 Node.js 入门 - 2.3 process

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  9. 极简 Node.js 入门 - 2.4 定时器

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

随机推荐

  1. oracle之三手工完全恢复

    手工完全恢复 3.1 完全恢复:通过备份.归档日志.current log ,将database恢复到failure 前的最后一次commit状态. 3.2 完全恢复的步骤 1)restore: OS ...

  2. HTML页面的基本信息

    1.python中生成的html页面,每一段的基本解释,以及header中的应用 2.body中的应用 2.1.a href链接点击baidu直接跳转百度网址,如果需要重新打开一个页面,详情看2.16 ...

  3. 掌控安全less6 靶场简易--盲注

    1.判断是否存在sql注入 http://injectx1.lab.aqlab.cn:81/Pass-11/index.php?id=1"  and "1"=" ...

  4. Kubernetes K8S之Service服务详解与示例

    K8S之Service概述与代理说明,并详解所有的service服务类型与示例 主机配置规划 服务器名称(hostname) 系统版本 配置 内网IP 外网IP(模拟) k8s-master Cent ...

  5. yum管理——linux字符界面安装图形化及两种界面的切换(3)

    1.查看yum软件包组 yum groups list 2.选择安装带 GUI 的服务器 yum groups install "带 GUI 的服务器" 3.字符界面切换为图形化界 ...

  6. AtomicInteger原理&源码分析

    转自https://www.cnblogs.com/rever/p/8215743.html 深入解析Java AtomicInteger原子类型 在进行并发编程的时候我们需要确保程序在被多个线程并发 ...

  7. Java审计之文件操作漏洞

    Java审计之文件操作漏洞篇 0x00 前言 本篇内容打算把Java审计中会遇到的一些文件操作的漏洞,都给叙述一遍.比如一些任意文件上传,文件下载,文件读取,文件删除,这些操作文件的漏洞. 0x01 ...

  8. Spring Cloud Alibaba生态探索:Dubbo、Nacos及Sentinel的完美结合

    @ 目录 背景 一.项目框架 1.1 采用IDEA和Maven多模块进行项目搭建 1.2 模块管理及版本管理 二.微服务公共接口 2.1 定义一个公共接口Api 2.2 pom.xml 2.3 Goo ...

  9. 堆的源码与应用:堆排序、优先队列、TopK问题

    1.堆 堆(Heap))是一种重要的数据结构,是实现优先队列(Priority Queues)首选的数据结构.由于堆有很多种变体,包括二项式堆.斐波那契堆等,但是这里只考虑最常见的就是二叉堆(以下简称 ...

  10. 刷题[安恒DASCTF2020四月春季赛]Ez unserialize

    解题思路 打开直接源码,没别的,审就完事了 代码审计 <?php show_source("index.php"); function write($data) { retu ...