-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathsink.js
54 lines (43 loc) · 1.22 KB
/
sink.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
42
43
44
45
46
47
48
49
50
51
52
53
54
var ready = require('./ready');
/**
### `sink(socket, opts?)`
Create a pull-stream `Sink` that will write data to the `socket`.
<<< examples/write.js
**/
var nextTick = typeof setImmediate !== 'undefined' ? setImmediate : process.nextTick
module.exports = function(socket, opts) {
return function (read) {
opts = opts || {}
var closeOnEnd = opts.closeOnEnd !== false;
var onClose = 'function' === typeof opts ? opts : opts.onClose;
function next(end, data) {
// if the stream has ended, simply return
if (end) {
if (closeOnEnd && socket.readyState <= 1) {
if(onClose)
socket.addEventListener('close', function (ev) {
if(ev.wasClean || ev.code === 1006) onClose()
else {
var err = new Error('ws error')
err.event = ev
onClose(err)
}
});
socket.close()
}
return;
}
// socket ready?
ready(socket, function(end) {
if (end) {
return read(end, function () {});
}
socket.send(data);
nextTick(function() {
read(null, next);
});
});
}
read(null, next);
}
}