-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnstream.js
More file actions
74 lines (56 loc) · 1.55 KB
/
nstream.js
File metadata and controls
74 lines (56 loc) · 1.55 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
64
65
66
67
68
69
70
71
72
73
74
/**
* stream.js - my stream implementation.
*
* 2010, Michel Beloshitsky
*
* Licensed under the terms of MIT license. See COPYING file in the
* root of distribution.
*/
var net = require('net')
exports.make = function (port, host, enc) {
var netStr = net.createConnection(port || TTDEFPORT, host)
var closed = false, encoding = enc || 'utf8'
var drainCallback = null, readCallback = null, buffer = '', requestedSize = 0
function checkReceivedEnough () {
if (requestedSize && buffer.length >= requestedSize) {
var resStr = buffer.substr(0, requestedSize)
buffer = buffer.slice(requestedSize)
requestedSize = 0
readCallback(null, resStr)
}
}
function write(str, cb) {
drainCallback = cb
netStr.write(str, encoding)
}
function read(size, cb) {
readCallback = cb
requestedSize = size
checkReceivedEnough()
}
function close() {
closed = true
netStr.destroy()
}
/* Event handlers */
netStr.addListener('connect' , function () {
netStr.setEncoding(encoding)
})
netStr.addListener('end' , function () {
})
netStr.addListener('data' , function (data) {
buffer += data
checkReceivedEnough()
})
netStr.addListener('drain' , function () {
if (drainCallback) {
drainCallback()
drainCallback = null
}
})
function extListener(event, fun) {
netStr.addListener(event, fun)
}
/* Public interface */
return {read:read, write:write, close:close, on: extListener}
}