-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
60 lines (51 loc) · 1.26 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';
var Itach;
var net = require('net');
var next = function (cmd, cb) {
cmd.shift();
if (typeof cmd[0] === 'number') {
return setTimeout(function () { return next(cmd, cb); }, cmd[0]);
}
return cb(cmd);
};
module.exports = Itach = function (host) {
this.host = host;
};
Itach.prototype.send = function (command, callback) {
var err;
var res = [];
var socket = new net.Socket();
if (!this.host) {
return callback(new Error('No host'));
}
if (!Array.isArray(command)) {
command = [command];
}
if (typeof command[0] === 'number') {
return callback(new Error('First element has to be a command (string)'));
}
socket.setEncoding('ASCII');
socket.connect(4998, this.host);
socket.on('data', function (chunk) {
res.push(chunk);
next(command, function (cmd) {
command = cmd;
if (command.length !== 0 && command[0]) {
socket.write(command[0], 'ASCII');
} else {
socket.end();
}
});
});
socket.on('error', function (error) {
err = error; // error with connection, closes socket
});
socket.on('close', function () {
if (err) {
return callback(err);
}
return callback(null, res);
});
// write first command
socket.write(command[0], 'ASCII');
};