-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
78 lines (62 loc) · 1.85 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var extend = require('util')._extend;
var util = require('util');
var split = require('split');
var Socket = require('net').Socket;
function QMP() {
QMP.super_.call(this);
this._commands = [];
};
util.inherits(QMP, Socket);
QMP.prototype.execute = function(command, arguments, callback) {
if (typeof arguments === 'function') {
callback = arguments;
arguments = null;
}
this._commands.push(callback);
if (arguments) {
this.write(JSON.stringify({execute:command, arguments:arguments}));
} else {
this.write(JSON.stringify({execute:command}));
}
};
QMP.prototype.connect = function(port, host, callback) {
if (typeof host === 'function') {
callback = host;
host = null;
}
if (typeof port !== 'number') {
// UNIX socket
QMP.super_.prototype.connect.call(this, port);
} else {
QMP.super_.prototype.connect.call(this, port, host);
}
this.once('connect', function() {
this.removeAllListeners('error');
});
this.once('error', function(err) {
if (callback) callback(err);
});
this.once('data', function(data) {
extend(this, JSON.parse(data).QMP);
this.execute('qmp_capabilities');
// Split response by line
this.pipe(split()).on('data', (function(line) {
if (!line) return this.end();
var json = JSON.parse(line);
if (json.return || json.error) {
var callback = this._commands.shift();
var error = (json.error) ? new Error(json.error.desc) : null;
if (callback) callback.apply(this, [error, json.return]);
if (error && !callback) this.emit('error', error);
} else if (json.event) {
// Emit QMP events
this.emit(json.event.toLowerCase(), json.event);
}
}).bind(this));
if (callback) callback.apply(this, [null, this]);
});
this.once('close', function() {
this.end();
});
};
module.exports = QMP;