-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (53 loc) · 1.4 KB
/
index.js
File metadata and controls
63 lines (53 loc) · 1.4 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
/**
* @module streamss-readonly
* @copyright 2015 commenthol
* @license MIT
*
* Code inspired by [read-only-stream](https://github.com/substack/read-only-stream) project. (MIT-licensed)
*/
'use strict'
const { Readable } = require('stream')
/**
* Converts any stream into a read-only stream
* @param {Readable|Transform|Duplex} stream - A stream which shall behave as a Readable only stream.
* @throws {Error} "not a readable stream" - if stream does not implement a Readable component this error is thrown
* @return {Readable} - A read-only readable stream
*/
function readonly (stream) {
const rs = stream._readableState || {}
const opts = {}
if (typeof stream.read !== 'function') {
throw new Error('not a readable stream')
}
;['highWaterMark', 'encoding', 'objectMode'].forEach(p => {
opts[p] = rs[p]
})
const readOnly = new Readable(opts)
let waiting = false
stream.on('readable', () => {
if (waiting) {
waiting = false
readOnly._read()
}
})
readOnly._read = function (size) {
let buf
while ((buf = stream.read(size)) !== null) {
if (!readOnly.push(buf)) {
return
}
}
waiting = true
}
stream.once('end', () => {
readOnly.push(null)
})
stream.once('close', () => {
readOnly.emit('close')
})
stream.on('error', (err) => {
readOnly.emit('error', err)
})
return readOnly
}
module.exports = readonly