/
server.js
executable file
·64 lines (54 loc) · 1.57 KB
/
server.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
const colors = require('colors/safe');
const fs = require('fs');
const path = require('path');
const os = require('os');
const ecstatic = require('ecstatic');
const union = require('union');
const PORT = 8080;
if (!process.argv[2]) {
fail('You need to specify a snippet. E.g.: \n npm start button.js');
}
let fileName = `${path.parse(process.argv[2]).name}.js`;
if (!exists(fileName)) {
fail('Snippet does not exist.');
}
let externalAddresses = getExternalAddresses();
if (!externalAddresses.length) {
fail('No remotely accessible network interfaces.');
}
let servePackageJson = (req, res, next) => {
if (req.url === '/package.json') {
return res.end(JSON.stringify({main: fileName}));
}
next();
};
let server = union.createServer({
before: [servePackageJson, ecstatic({root: path.join(__dirname, '..')})]
});
server.listen(PORT, () => {
let port = server.address().port;
console.log(
colors.yellow(`Server started for ${colors.red.bold(fileName)}.\nPoint your Tabris.js client to:`)
);
externalAddresses.forEach(
iface => console.log(colors.green(' http://' + iface.address + ':' + port.toString()))
);
});
function getExternalAddresses() {
let interfaces = os.networkInterfaces();
return Object.keys(interfaces)
.map(key => interfaces[key].find(details => details.family === 'IPv4' && details.internal === false))
.filter(val => !!val);
}
function fail(message) {
console.error(colors.red(message));
process.exit(1);
}
function exists(filePath) {
try {
fs.accessSync(filePath);
return true;
} catch(e) {
return false;
}
}