1 | 'use strict'
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const { Transform } = require('stream')
|
13 | const common = require('./common')
|
14 |
|
15 | module.exports = class DelayedBody extends Transform {
|
16 | constructor(ms, body) {
|
17 | super()
|
18 |
|
19 | const self = this
|
20 | let data = ''
|
21 | let ended = false
|
22 |
|
23 | if (common.isStream(body)) {
|
24 | body.on('data', function(chunk) {
|
25 | data += Buffer.isBuffer(chunk) ? chunk.toString() : chunk
|
26 | })
|
27 |
|
28 | body.once('end', function() {
|
29 | ended = true
|
30 | })
|
31 |
|
32 | body.resume()
|
33 | }
|
34 |
|
35 |
|
36 |
|
37 | common.setTimeout(function() {
|
38 | if (common.isStream(body) && !ended) {
|
39 | body.once('end', function() {
|
40 | self.end(data)
|
41 | })
|
42 | } else {
|
43 | self.end(data || body)
|
44 | }
|
45 | }, ms)
|
46 | }
|
47 |
|
48 | _transform(chunk, encoding, cb) {
|
49 | this.push(chunk)
|
50 | process.nextTick(cb)
|
51 | }
|
52 | }
|