forked from IlyaBiryukov/message-boundary-node-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (31 loc) · 1.08 KB
/
index.js
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
/* global Buffer */
var split = require('split');
var through = require('through');
function splitJoinStream(readable, target, writable, delimiter) {
var delimiterBuffer;
if (!readable && !writable) {
throw new Error('readable and writeable are both not defined. At least one of them should be specified.');
}
if (!target) {
throw new Error('target is not defined');
}
if (delimiter === undefined) {
delimiter = '\0';
}
else if (delimiter === '') {
throw new Error('delimiter cannot be an empty string');
}
if (readable) {
readable.pipe(split(delimiter, null, {trailing: false})).pipe(target);
}
if (writable) {
delimiterBuffer = new Buffer(delimiter);
target.pipe(through(addDelmiter)).pipe(writable);
}
return target;
function addDelmiter(chunk) {
var newChunk = Buffer.isBuffer(chunk) ? Buffer.concat([chunk, delimiterBuffer]) : chunk.concat(delimiter);
this.queue(newChunk);
}
}
module.exports = splitJoinStream;