国产99久久精品_欧美日本韩国一区二区_激情小说综合网_欧美一级二级视频_午夜av电影_日本久久精品视频

最新文章專題視頻專題問答1問答10問答100問答1000問答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
當(dāng)前位置: 首頁 - 科技 - 知識(shí)百科 - 正文

node的靜態(tài)文件服務(wù)器如何使用

來源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 19:58:01
文檔

node的靜態(tài)文件服務(wù)器如何使用

node的靜態(tài)文件服務(wù)器如何使用:這次給大家?guī)韓ode的靜態(tài)文件服務(wù)器如何使用,使用node靜態(tài)文件服務(wù)器的注意事項(xiàng)有哪些,下面就是實(shí)戰(zhàn)案例,一起來看一下。本篇文章主要介紹了實(shí)戰(zhàn)node靜態(tài)文件服務(wù)器的示例,分享給大家,具體如下:支持功能:讀取靜態(tài)文件訪問目錄可以自動(dòng)尋找下面的ind
推薦度:
導(dǎo)讀node的靜態(tài)文件服務(wù)器如何使用:這次給大家?guī)韓ode的靜態(tài)文件服務(wù)器如何使用,使用node靜態(tài)文件服務(wù)器的注意事項(xiàng)有哪些,下面就是實(shí)戰(zhàn)案例,一起來看一下。本篇文章主要介紹了實(shí)戰(zhàn)node靜態(tài)文件服務(wù)器的示例,分享給大家,具體如下:支持功能:讀取靜態(tài)文件訪問目錄可以自動(dòng)尋找下面的ind

這次給大家?guī)韓ode的靜態(tài)文件服務(wù)器如何使用,使用node靜態(tài)文件服務(wù)器的注意事項(xiàng)有哪些,下面就是實(shí)戰(zhàn)案例,一起來看一下。

本篇文章主要介紹了實(shí)戰(zhàn)node靜態(tài)文件服務(wù)器的示例,分享給大家,具體如下:

支持功能:

  1. 讀取靜態(tài)文件

  2. 訪問目錄可以自動(dòng)尋找下面的index.html文件, 如果沒有index.html則列出文件列表

  3. MIME類型支持

  4. 緩存支持/控制

  5. 支持gzip壓縮

  6. Range支持,斷點(diǎn)續(xù)傳

  7. 全局命令執(zhí)行

  8. 子進(jìn)程運(yùn)行

1. 創(chuàng)建服務(wù)讀取靜態(tài)文件

首先引入http模塊,創(chuàng)建一個(gè)服務(wù)器,并監(jiān)聽配置端口:

 const http = require('http');
 
 const server = http.createServer();
 
 // 監(jiān)聽請求
 server.on('request', request.bind(this));
 
 server.listen(config.port, () => {
 console.log(`靜態(tài)文件服務(wù)啟動(dòng)成功, 訪問localhost:${config.port}`);
 });

寫一個(gè)fn專門處理請求, 返回靜態(tài)文件, url模塊獲取路徑:

 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); // 讀取文件,并響應(yīng)
 }

支持尋找index.html:

 if (pathname === '/') {
 const rootPath = path.join(config.root, 'index.html');
 try{
 const indexStat = fs.statSync(rootPath);
 if (indexStat) {
 filepath = rootPath;
 }
 } catch(e) {
 
 }
 }

訪問目錄時(shí),列出文件目錄:

 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模板:

 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靜態(tài)文件服務(wù)器</h1>
 <ul>
 {{#each files}}
 <li>
 <a href={{url}}>{{name}}</a>
 </li>
 {{/each}}
 </ul>
 </body>
 </html>

2.MIME類型支持

利用mime模塊得到文件類型,并設(shè)置編碼:

res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');

3.緩存支持

http協(xié)議緩存:

Cache-Control: http1.1內(nèi)容,告訴客戶端如何緩存數(shù)據(jù),以及規(guī)則

  1. private 客戶端可以緩存

  2. public 客戶端和代理服務(wù)器都可以緩存

  3. max-age=60 緩存內(nèi)容將在60秒后失效

  4. no-cache 需要使用對比緩存驗(yàn)證數(shù)據(jù),強(qiáng)制向源服務(wù)器再次驗(yàn)證

  5. no-store 所有內(nèi)容都不會(huì)緩存,強(qiáng)制緩存和對比緩存都不會(huì)觸發(fā)

Expires: http1.0內(nèi)容,cache-control會(huì)覆蓋,告訴客戶端緩存什么時(shí)候過期

ETag: 內(nèi)容的hash值 下一次客戶端請求在請求頭里添加if-none-match: etag值

Last-Modified: 最后的修改時(shí)間 下一次客戶端請求在請求頭里添加if-modified-since: Last-Modified值

 handleCache(req, res, stats, hash) {
 // 當(dāng)資源過期時(shí), 客戶端發(fā)現(xiàn)上一次請求資源,服務(wù)器有發(fā)送Last-Modified, 則再次請求時(shí)帶上if-modified-since
 const ifModifiedSince = req.headers['if-modified-since'];
 // 服務(wù)器發(fā)送了etag,客戶端再次請求時(shí)用If-None-Match字段來詢問是否過期
 const ifNoneMatch = req.headers['if-none-match'];
 // http1.1內(nèi)容 max-age=30 為強(qiáng)行緩存30秒 30秒內(nèi)再次請求則用緩存 private 僅客戶端緩存,代理服務(wù)器不可緩存
 res.setHeader('Cache-Control', 'private,max-age=30');
 // http1.0內(nèi)容 作用與Cache-Control一致 告訴客戶端什么時(shí)間,資源過期 優(yōu)先級低于Cache-Control
 res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toGMTString());
 // 設(shè)置ETag 根據(jù)內(nèi)容生成的hash
 res.setHeader('ETag', hash);
 // 設(shè)置Last-Modified 文件最后修改時(shí)間
 const lastModified = stats.ctime.toGMTString();
 res.setHeader('Last-Modified', lastModified);
 
 // 判斷ETag是否過期
 if (ifNoneMatch && ifNoneMatch != hash) {
 return false;
 }
 // 判斷文件最后修改時(shí)間
 if (ifModifiedSince && ifModifiedSince != lastModified) {
 return false;
 }
 // 如果存在且相等,走緩存304
 if (ifNoneMatch || ifModifiedSince) {
 res.writeHead(304);
 res.end();
 return true;
 } else {
 return false;
 }
 }

4.壓縮

客戶端發(fā)送內(nèi)容,通過請求頭里Accept-Encoding: gzip, deflate告訴服務(wù)器支持哪些壓縮格式,服務(wù)器根據(jù)支持的壓縮格式,壓縮內(nèi)容。如服務(wù)器不支持,則不壓縮。

 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;
 }
 }

5.斷點(diǎn)續(xù)傳

服務(wù)器通過請求頭中的Range: bytes=0-xxx來判斷是否是做Range請求,如果這個(gè)值存在而且有效,則只發(fā)回請求的那部分文件內(nèi)容,響應(yīng)的狀態(tài)碼變成206,表示Partial Content,并設(shè)置Content-Range。如果無效,則返回416狀態(tài)碼,表明Request Range Not Satisfiable。如果不包含Range的請求頭,則繼續(xù)通過常規(guī)的方式響應(yīng)。

 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;//返回整個(gè)內(nèi)容的一塊
 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
 });
 }

6.全局命令執(zhí)行

通過npm link實(shí)現(xiàn)

  1. 為npm包目錄創(chuàng)建軟鏈接,將其鏈到{prefix}/lib/node_modules/

  2. 為可執(zhí)行文件(bin)創(chuàng)建軟鏈接,將其鏈到{prefix}/bin/{name}

npm link命令通過鏈接目錄和可執(zhí)行文件,實(shí)現(xiàn)npm包命令的全局可執(zhí)行。

package.json里面配置

 {
 bin: {
 "hope-server": "bin/hope"
 }
 }

在項(xiàng)目下面創(chuàng)建bin目錄 hope文件, 利用yargs配置命令行傳參數(shù)

 // 告訴電腦用node運(yùn)行我的文件
 #! /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: '靜態(tài)文件根目錄'
 }).option('o', {
 alias: 'host',
 demand: 'false',
 default: 'localhost',
 type: 'string',
 description: '配置監(jiān)聽的主機(jī)'
 }).option('p', {
 alias: 'port',
 demand: 'false',
 type: 'number',
 default: 8080,
 description: '配置端口號(hào)'
 }).option('c', {
 alias: 'child',
 demand: 'false',
 type: 'boolean',
 default: false,
 description: '是否子進(jìn)程運(yùn)行'
 })
 .usage('hope-server [options]')
 .example(
 'hope-server -d / -p 9090 -o localhost', '在本機(jī)的9090端口上監(jiān)聽客戶端的請求'
 ).help('h').argv;
 
 // 啟動(dòng)服務(wù)
 init(argv);

7.子進(jìn)程運(yùn)行

通過spawn實(shí)現(xiàn)

index.js

 const { spawn } = require('child_process');
 const Server = require('./hope');
 
 function init(argv) {
 // 如果配置為子進(jìn)程開啟服務(wù)
 if (argv.child) {
 //子進(jìn)程啟動(dòng)服務(wù)
 const child = spawn('node', ['hope.js', JSON.stringify(argv)], {
 cwd: dirname,
 detached: true,
 stdio: 'inherit'
 });
 
 //后臺(tái)運(yùn)行
 child.unref();
 //退出主線程,讓子線程單獨(dú)運(yùn)行
 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();
 }

8.源碼及測試

源碼地址: hope-server

npm install hope-server -g

進(jìn)入任意目錄

hope-server

相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!

推薦閱讀:

解決vue2.0路由不顯示router-view的問題

在vue里如何使用xe-utils

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

node的靜態(tài)文件服務(wù)器如何使用

node的靜態(tài)文件服務(wù)器如何使用:這次給大家?guī)韓ode的靜態(tài)文件服務(wù)器如何使用,使用node靜態(tài)文件服務(wù)器的注意事項(xiàng)有哪些,下面就是實(shí)戰(zhàn)案例,一起來看一下。本篇文章主要介紹了實(shí)戰(zhàn)node靜態(tài)文件服務(wù)器的示例,分享給大家,具體如下:支持功能:讀取靜態(tài)文件訪問目錄可以自動(dòng)尋找下面的ind
推薦度:
標(biāo)簽: 使用 服務(wù)器 js文件
  • 熱門焦點(diǎn)

最新推薦

猜你喜歡

熱門推薦

專題
Top
主站蜘蛛池模板: 国产精品合集一区二区三区 | 日韩精品成人 | 欧美系列在线 | 国产精品亚洲一区二区三区在线播放 | 国产91精品一区二区视色 | 91一区二区三区 | 亚洲欧美一区二区三区国产精品 | 国内一区二区三区精品视频 | 日韩专区欧美 | 伊人一级 | 亚洲精品一线二线三线 | 欧美1页| 一级黄毛片 | 国产精品免费播放 | 91在线 | 欧美: | 欧美一区二区在线观看免费网站 | 久久国产精品自由自在 | 国产精品手机视频一区二区 | 午夜高清在线观看免费完整版 | 99久久免费国产精精品 | 国产最新进精品视频 | 亚洲国产精品免费 | 一区二区影视 | 亚洲小视频在线 | 精品国产欧美一区二区三区成人 | 欧美色欧美亚洲另类 | 欧美三级经典电影在线观看 | 手机在线国产视频 | 国内精品一区二区三区最新 | 国产69久久精品成人看小说 | 国产一区二区三区精品视频 | 久久久久久国产a免费观看黄色大片 | 毛片视频网址 | 亚洲国产成人精品一区91 | 欧美精品高清 | 日韩伦理亚洲欧美在线一区 | va欧美国产在线视频 | 国产 欧美 日韩 在线 | 日韩高清专区 | 成人日韩在线 | 亚洲福利视频 |