forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefix-stream-write.js
More file actions
25 lines (20 loc) · 831 Bytes
/
prefix-stream-write.js
File metadata and controls
25 lines (20 loc) · 831 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
module.exports = function prefixStreamWrite (writableStream, prefix) {
const oldWrite = writableStream.write
function newWrite (...args) {
const [chunk, encoding] = args
// Prepend the prefix if the chunk is either a string or a Buffer.
// Otherwise, just leave it alone to be safe.
if (typeof chunk === 'string') {
// Only prepend the prefix is the `encoding` is safe or not provided.
// If it's a function, it is third arg `callback` provided as optional second
if (!encoding || encoding === 'utf8' || typeof encoding === 'function') {
args[0] = prefix + chunk
}
} else if (Buffer.isBuffer(chunk)) {
args[0] = Buffer.concat([Buffer.from(prefix), chunk])
}
return oldWrite.apply(this, args)
}
writableStream.write = newWrite
return writableStream
}