支持功能:javascript
首先引入http模塊,建立一個服務器,並監聽配置端口:html
const http = require('http');
const server = http.createServer();
// 監聽請求
server.on('request', request.bind(this));
server.listen(config.port, () => {
console.log(`靜態文件服務啓動成功, 訪問localhost:${config.port}`);
});
複製代碼
寫一個fn專門處理請求, 返回靜態文件, url模塊獲取路徑:java
const url = require('url');
const fs = require('fs');
function request(req, res) {
const { pathname } = url.parse(req.url); // 訪問路徑
const filepath = path.join(config.root, pathname); // 文件路徑
fs.createReadStream(filepath).pipe(res); // 讀取文件,並響應
}
複製代碼
支持尋找index.html:node
if (pathname === '/') {
const rootPath = path.join(config.root, 'index.html');
try{
const indexStat = fs.statSync(rootPath);
if (indexStat) {
filepath = rootPath;
}
} catch(e) {
}
}
複製代碼
訪問目錄時,列出文件目錄:git
fs.stat(filepath, (err, stats) => {
if (err) {
res.end('not found');
return;
}
if (stats.isDirectory()) {
let files = fs.readdirSync(filepath);
files = files.map(file => ({
name: file,
url: path.join(pathname, file)
}));
let html = this.list()({
title: pathname,
files
});
res.setHeader('Content-Type', 'text/html');
res.end(html);
}
}
複製代碼
html模板:github
function list() {
let tmpl = fs.readFileSync(path.resolve(__dirname, 'template', 'list.html'), 'utf8');
return handlebars.compile(tmpl);
}
複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{title}}</title>
</head>
<body>
<h1>hope-server靜態文件服務器</h1>
<ul>
{{#each files}}
<li>
<a href={{url}}>{{name}}</a>
</li>
{{/each}}
</ul>
</body>
</html>
複製代碼
利用mime模塊獲得文件類型,並設置編碼:npm
res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');
複製代碼
http協議緩存:json
handleCache(req, res, stats, hash) {
// 當資源過時時, 客戶端發現上一次請求資源,服務器有發送Last-Modified, 則再次請求時帶上if-modified-since
const ifModifiedSince = req.headers['if-modified-since'];
// 服務器發送了etag,客戶端再次請求時用If-None-Match字段來詢問是否過時
const ifNoneMatch = req.headers['if-none-match'];
// http1.1內容 max-age=30 爲強行緩存30秒 30秒內再次請求則用緩存 private 僅客戶端緩存,代理服務器不可緩存
res.setHeader('Cache-Control', 'private,max-age=30');
// http1.0內容 做用與Cache-Control一致 告訴客戶端什麼時間,資源過時 優先級低於Cache-Control
res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toGMTString());
// 設置ETag 根據內容生成的hash
res.setHeader('ETag', hash);
// 設置Last-Modified 文件最後修改時間
const lastModified = stats.ctime.toGMTString();
res.setHeader('Last-Modified', lastModified);
// 判斷ETag是否過時
if (ifNoneMatch && ifNoneMatch != hash) {
return false;
}
// 判斷文件最後修改時間
if (ifModifiedSince && ifModifiedSince != lastModified) {
return false;
}
// 若是存在且相等,走緩存304
if (ifNoneMatch || ifModifiedSince) {
res.writeHead(304);
res.end();
return true;
} else {
return false;
}
}
複製代碼
客戶端發送內容,經過請求頭裏Accept-Encoding: gzip, deflate告訴服務器支持哪些壓縮格式,服務器根據支持的壓縮格式,壓縮內容。如服務器不支持,則不壓縮。緩存
getEncoding(req, res) {
const acceptEncoding = req.headers['accept-encoding'];
// gzip和deflate壓縮
if (/\bgzip\b/.test(acceptEncoding)) {
res.setHeader('Content-Encoding', 'gzip');
return zlib.createGzip();
} else if (/\bdeflate\b/.test(acceptEncoding)) {
res.setHeader('Content-Encoding', 'deflate');
return zlib.createDeflate();
} else {
return null;
}
}
複製代碼
服務器經過請求頭中的Range: bytes=0-xxx來判斷是不是作Range請求,若是這個值存在並且有效,則只發回請求的那部分文件內容,響應的狀態碼變成206,表示Partial Content,並設置Content-Range。若是無效,則返回416狀態碼,代表Request Range Not Satisfiable。若是不包含Range的請求頭,則繼續經過常規的方式響應。bash
getStream(req, res, filepath, statObj) {
let start = 0;
let end = statObj.size - 1;
const range = req.headers['range'];
if (range) {
res.setHeader('Accept-Range', 'bytes');
res.statusCode = 206;//返回整個內容的一塊
let result = range.match(/bytes=(\d*)-(\d*)/);
if (result) {
start = isNaN(result[1]) ? start : parseInt(result[1]);
end = isNaN(result[2]) ? end : parseInt(result[2]) - 1;
}
}
return fs.createReadStream(filepath, {
start, end
});
}
複製代碼
經過npm link實現
npm link命令經過連接目錄和可執行文件,實現npm包命令的全局可執行。
package.json裏面配置
{
bin: {
"hope-server": "bin/hope"
}
}
複製代碼
在項目下面建立bin目錄 hope文件, 利用yargs配置命令行傳參數
// 告訴電腦用node運行個人文件
#! /usr/bin/env node
const yargs = require('yargs');
const init = require('../src/index.js');
const argv = yargs.option('d', {
alias: 'root',
demand: 'false',
type: 'string',
default: process.cwd(),
description: '靜態文件根目錄'
}).option('o', {
alias: 'host',
demand: 'false',
default: 'localhost',
type: 'string',
description: '配置監聽的主機'
}).option('p', {
alias: 'port',
demand: 'false',
type: 'number',
default: 8080,
description: '配置端口號'
}).option('c', {
alias: 'child',
demand: 'false',
type: 'boolean',
default: false,
description: '是否子進程運行'
})
.usage('hope-server [options]')
.example(
'hope-server -d / -p 9090 -o localhost', '在本機的9090端口上監聽客戶端的請求'
).help('h').argv;
// 啓動服務
init(argv);
複製代碼
經過spawn實現
index.js
const { spawn } = require('child_process');
const Server = require('./hope');
function init(argv) {
// 若是配置爲子進程開啓服務
if (argv.child) {
//子進程啓動服務
const child = spawn('node', ['hope.js', JSON.stringify(argv)], {
cwd: __dirname,
detached: true,
stdio: 'inherit'
});
//後臺運行
child.unref();
//退出主線程,讓子線程單獨運行
process.exit(0);
} else {
const server = new Server(argv);
server.start();
}
}
module.exports = init;
複製代碼
hope.js
if (process.argv[2] && process.argv[2].startsWith('{')) {
const argv = JSON.parse(process.argv[2]);
const server = new Hope(argv);
server.start();
}
複製代碼
源碼地址: hope-server
npm install hope-server -g
複製代碼
進入任意目錄
hope-server
複製代碼