aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/stream-replacer.ts
blob: 4babab41851acd9342f2ccd472961e68f59bbb78 (plain) (blame)
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 { Transform, TransformCallback } from 'stream'

// Thanks: https://stackoverflow.com/a/45126242
class StreamReplacer extends Transform {
  private pendingChunk: Buffer

  constructor (private readonly replacer: (line: string) => string) {
    super()
  }

  _transform (chunk: Buffer, _encoding: BufferEncoding, done: TransformCallback) {
    try {
      this.pendingChunk = this.pendingChunk?.length
        ? Buffer.concat([ this.pendingChunk, chunk ])
        : chunk

      let index: number

      // As long as we keep finding newlines, keep making slices of the buffer and push them to the
      // readable side of the transform stream
      while ((index = this.pendingChunk.indexOf('\n')) !== -1) {
        // The `end` parameter is non-inclusive, so increase it to include the newline we found
        const line = this.pendingChunk.slice(0, ++index)

        // `start` is inclusive, but we are already one char ahead of the newline -> all good
        this.pendingChunk = this.pendingChunk.slice(index)

        // We have a single line here! Prepend the string we want
        this.push(this.doReplace(line))
      }

      return done()
    } catch (err) {
      return done(err)
    }
  }

  _flush (done: TransformCallback) {
    // If we have any remaining data in the cache, send it out
    if (!this.pendingChunk?.length) return done()

    try {
      return done(null, this.doReplace(this.pendingChunk))
    } catch (err) {
      return done(err)
    }
  }

  private doReplace (buffer: Buffer) {
    const line = this.replacer(buffer.toString('utf8'))

    return Buffer.from(line, 'utf8')
  }
}

export {
  StreamReplacer
}