Repository navigation
Expand file tree
/
Copy pathNodeStreamUtils.ts
More file actions
93 lines (85 loc) · 2.78 KB
/
Copy pathNodeStreamUtils.ts
File metadata and controls
93 lines (85 loc) · 2.78 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (c) 2022-2023. Heusala Group Oy <info@heusalagroup.fi>. All rights reserved.
// Copyright (c) 2020-2021. Sendanor <info@sendanor.fi>. All rights reserved.
import { parse as queryParse } from "querystring";
import { Readable } from "stream";
import { JsonAny } from "../core/Json";
/**
* The type definitions for Node were inciting to use strict type list, even though NodeJS manual
* tells just "string".
*/
export type BufferEncodingString = "utf-8" | "ascii" | "utf8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" | undefined;
export class NodeStreamUtils {
/**
* Read stream data as Buffer object.
*
* @param request
* @return The request input data
*/
public static async getStreamDataAsBuffer (
request : Readable
) : Promise<Buffer> {
return new Promise( (resolve, reject) => {
const chunks : Buffer[] = [];
request.on('data', (chunk : Buffer) => {
try {
chunks.push(chunk);
} catch(err) {
reject(err);
}
});
request.on('end', () => {
try {
resolve( Buffer.concat(chunks) );
} catch(err) {
reject(err);
}
});
});
}
/**
* Read stream data as string.
*
* @param request
* @param encoding
* @return The request input data
*/
public static async getStreamDataAsString (
request : Readable,
encoding : BufferEncodingString = 'utf8'
) : Promise<string> {
const buffer = await NodeStreamUtils.getStreamDataAsBuffer(request);
return buffer.toString(encoding);
}
/**
* Read stream data as "application/x-www-form-urlencoded".
*
* @param request
* @return The request input data. If request data is an empty string, an `undefined` will be
* returned.
*/
public static async getStreamDataAsFormUrlEncoded (
request : Readable
) : Promise<JsonAny | undefined> {
const dataString = await NodeStreamUtils.getStreamDataAsString(request);
if (dataString === "") {
return undefined;
}
return queryParse(dataString);
}
/**
* Read stream data as JSON.
*
* @param request
* @return The request input data. If request data is an empty string, an `undefined` will be
* returned.
*/
public static async getStreamDataAsJson (
request : Readable
) : Promise<JsonAny | undefined> {
const dataString = await NodeStreamUtils.getStreamDataAsString(request);
if (dataString === "") {
return undefined;
}
return JSON.parse(dataString);
}
}