/
LocalTunnel.js
69 lines (61 loc) · 1.58 KB
/
LocalTunnel.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
function LocalTunnel(port, binary) {
var self = this,
child,
started = false;
if (!binary) {
binary = 'localtunnel';
}
process.on("exit", function(code, signal) {
if (child) {
child.kill(signal);
}
});
self.start = function(callback) {
if (started) {
callback(new Error('local tunnel already started'));
} else {
var stdoutData = '';
var stdout;
if (process.platform === 'win32') {
child = require('child_process').spawn('cmd', ['/s', '/c', binary, port]);
stdout = child.stdout;
child.stderr.on('data', function(data) {
stdoutData += data;
});
} else {
stdout = child = require('pty.js').spawn(binary, [port], {
name: 'localtunnel',
cols: 80,
rows: 30
});
}
child.on('exit', function(code, signal) {
if (!started) {
callback(new Error('localtunnel failed to start:\n' + stdoutData));
}
child = null;
});
stdout.setEncoding();
stdout.on('data', function(data) {
stdoutData += data.toString();
var match = stdoutData.match(/[a-z0-9]{4}\.localtunnel\.com/g);
if (match) {
started = true;
callback(null, match[0]);
}
});
}
};
self.stop = function(callback) {
if (!started) {
callback(new Error('localtunnel not active'));
} else {
child.on('exit', function(code, signal) {
started = false;
callback();
});
child.kill();
}
};
}
module.exports = LocalTunnel;