-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathindex.mjs
More file actions
58 lines (54 loc) · 1.23 KB
/
index.mjs
File metadata and controls
58 lines (54 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { IncomingMessage, ServerResponse } from 'http';
// IncomingMessage
class Request {
constructor(method = 'GET', headers = {}) {
this.method = method.toUpperCase();
this.headers = {};
for (let i in headers) {
this.headers[i.toLowerCase()] = headers[i];
}
}
}
class Response extends ServerResponse {
constructor(req) {
super(req);
this._chunks = [];
this.done = new Promise(r => this._done = r);
}
write(chunk, enc, cb) {
if (!Buffer.isBuffer(chunk)) chunk = Buffer.from(chunk, enc);
this._chunks.push(chunk);
if (cb) cb(null);
return true;
}
end(chunk, enc, cb) {
if (chunk) this.write(chunk, enc);
if (cb) cb();
this._done(Buffer.concat(this._chunks));
return this;
}
getResponseData() {
return this.done;
}
async getResponseText() {
return (await this.done).toString();
}
}
/**
* @param {string} method
* @param {string} encoding
* @returns {{ req: IncomingMessage, res: Response }}
*/
export function prepare(method, encoding) {
let req = new Request(method, {
'Accept-Encoding': encoding,
});
let res = new Response(req);
// @ts-expect-error
return { req, res };
}
export function toAscii(thing) {
return JSON.stringify(
Buffer.from(thing).toString('ascii')
).replace(/(^"|"$)/g,'');
}