增加静态文件load方法, 不强制为下载; 优化头信息设置; 增加缓存快捷设置
parent
08576a85e0
commit
1021ef2666
36
index.js
36
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) {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@gm5/response",
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.0",
|
||||
"type": "module",
|
||||
"description": "对Http的response进一步封装, 提供常用的API",
|
||||
"main": "index.js",
|
||||
|
|
Loading…
Reference in New Issue