From 1021ef266641f162c1450cf44b4a458f98cd7c38 Mon Sep 17 00:00:00 2001 From: yutent Date: Thu, 18 Jul 2024 10:03:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=9D=99=E6=80=81=E6=96=87?= =?UTF-8?q?=E4=BB=B6load=E6=96=B9=E6=B3=95,=20=E4=B8=8D=E5=BC=BA=E5=88=B6?= =?UTF-8?q?=E4=B8=BA=E4=B8=8B=E8=BD=BD;=20=E4=BC=98=E5=8C=96=E5=A4=B4?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=E8=AE=BE=E7=BD=AE;=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E5=BF=AB=E6=8D=B7=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 36 ++++++++++++++++++++++++++++++++---- package.json | 2 +- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 38e8818..1a23c3d 100644 --- a/index.js +++ b/index.js @@ -56,6 +56,15 @@ export default class Response { this.#res.end(buf) } + /** + * 设置缓存时长, 单位秒 + */ + set expires(time = 3600) { + let t = new Date(Date.now() + time * 1000) + this.set('Expires', t.toGMTString()) + this.set('Cache-Control', 'max-age=' + time) + } + /** * [error http 错误显示] * @param {Number} code [http错误码] @@ -108,7 +117,7 @@ export default class Response { data += '' data = data || STATUS_TEXT[this.status] this.type = 'html' - this.set('Content-Length', Buffer.byteLength(data)) + this.length = Buffer.byteLength(data) this.body = data } @@ -142,6 +151,8 @@ export default class Response { } } + this.expires = 3600 + if (Buffer.isBuffer(target)) { data = target } else { @@ -156,7 +167,7 @@ export default class Response { size = end - start } } - this.set('Content-Length', size) + this.length = size return fs.origin .createReadStream(target, { start, end }) .pipe(this.#res) @@ -169,10 +180,27 @@ export default class Response { data = data.slice(start, end) } - this.set('Content-Length', data.length) + this.length = data.length this.body = data } + load(file, type) { + let stat = fs.stat(file) + if (stat.isFile()) { + let size = stat.size + + let _type = type || file.split('.').pop() || 'stream' + + this.expires = 30 * 24 * 3600 + this.type = _type + this.length = stat.size + return fs.origin.createReadStream(file).pipe(this.#res) + } else { + this.status = 404 + this.body = null + } + } + /** * [send json格式输出] * @param {Num} code [返回码] @@ -196,7 +224,7 @@ export default class Response { output = JSON.stringify({ code, msg, data }) this.type = 'json' - this.set('Content-Length', Buffer.byteLength(output)) + this.length = Buffer.byteLength(output) // 只设置200以上的值 if (code && code >= 200 && code <= 599) { diff --git a/package.json b/package.json index 543484d..b5dbdc9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@gm5/response", - "version": "2.0.2", + "version": "2.1.0", "type": "module", "description": "对Http的response进一步封装, 提供常用的API", "main": "index.js",