一、编写服务程序
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const zlib = require('zlib'); // gzip压缩模块
const mime = require('mime-types'); // 需npm安装
/**
* 静态服务器
* @param {String} options.hostname 主机
* @param {Number} options.port 端口
* @param {String} options.root 静态资源目录
* @param {String} options.index 入口页面
* @param {Boolean} options.gzip 是否开启gzip压缩
* @param {String} options.compress 指定压缩的文件格式(多个格式中间以|分隔)
* @param {Boolean} options.openBrowser 自动打开默认浏览器
*/
function staticServer(options) {
const defaults = {
hostname: 'localhost',
port: 80,
root: '../dist',
index: 'index.html',
gzip: true,
compress: 'html|css|js',
openBrowser: false
};
const settings = Object.assign({
}, defaults, options); // 合并配置
const rootPath = path.join(__dirname, settings.root); // 获取静态根目录路径

本文介绍如何使用Node.js构建一个静态服务器,包括设置主机、端口、资源目录、文件压缩等,并提供了一个完整的示例。重点讲解了gzip压缩和文件类型判断功能。
最低0.47元/天 解锁文章
630

被折叠的 条评论
为什么被折叠?



