forked from heapwolf/liveswap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
64 lines (52 loc) · 1.33 KB
/
client.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
55
56
57
58
59
60
61
62
63
var through = require('through')
var parse = require('through-parse')
var split = require('split')
var net = require('net')
//
// send a command to the liveswap server over tcp
// using a simple JSON protocol.
//
var exec = exports.exec = function(args) {
var options;
if (typeof args[0] == 'function') {
options = {}
}
else if (typeof args[0] == 'string') {
options = { value: args[0] }
}
else {
options = args[0] || {}
}
var cmd = options.cmd || args.callee.name
var value = options.value || ''
var port = options.port || 3000
var host = options.host || '127.0.0.1'
var cb = args[1]
if (!cb) {
throw new Error('callback required');
}
var stream = net.connect(port, host, function() {
var message = { cmd: cmd, value: value }
stream.write(JSON.stringify(message) + '\n')
})
var fin
stream.on('error', function(err) {
if (!fin) {
fin = true
cb(err)
}
})
stream
.pipe(split())
.pipe(parse())
.on('data', function(data) {
if (!fin && data.cmd == cmd) {
cb(null, data)
}
})
return stream
}
exports.upgrade = function upgrade() { return exec(arguments) }
exports.kill = function kill() { return exec(arguments) }
exports.die = function die() { return exec(arguments) }
exports.message = function message() { return exec(arguments) }