-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathStringWriter.ts
More file actions
30 lines (25 loc) · 978 Bytes
/
StringWriter.ts
File metadata and controls
30 lines (25 loc) · 978 Bytes
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
import { Writable } from "stream"
import { StringEncoding } from "./StringEncoding"
export class StringWriter extends Writable {
protected byteLength = 0
protected bufs: Buffer<ArrayBuffer>[] = []
constructor(protected maxByteLength: number = 1 * 1024 * 1024) {
super()
}
_write(chunk: Buffer | string | any, _: string, callback: (error: Error | null) => void) {
if (!(chunk instanceof Buffer)) {
callback(new Error("StringWriter: expects chunks of type 'Buffer'."))
return
}
if (this.byteLength + chunk.byteLength > this.maxByteLength) {
callback(new Error(`StringWriter: Maximum bytes exceeded, maxByteLength=${this.maxByteLength}.`))
return
}
this.byteLength += chunk.byteLength
this.bufs.push(chunk)
callback(null)
}
getText(encoding: StringEncoding) {
return Buffer.concat(this.bufs).toString(encoding);
}
}