-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
82 lines (69 loc) · 2.32 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
79
80
81
82
#!/usr/bin/env node
// TODO: Implement Search Bar
const opn = require('opn');
const express = require('express');
const app = express();
const qr = require('qr-image');
const pngStringify = require('console-png');
const getInterfaceAddress = require('./server/getInterfaceAddress');
const route = require('./server/routes');
const storage = require('node-persist');
const fs = require('fs');
const path = require('path');
const devEnv = process.env.NODE_ENV && process.env.NODE_ENV.trim() === 'development';
// Clear Uploads
const directory = 'uploads';
fs.readdir(directory, (err, files) => {
// Skipping error because it simply means that the directory is not created yet. It will be fixed automatically later.
if (!err) {
for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
}
});
app.locals.files = [];
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
const createServer = (address) => {
let options = [0, address];
if (devEnv) {
options = [8000];
}
let server = app.listen(...options, async () => {
const serverAcquiredAddress = `http://${server.address().address}:${server.address().port}`;
console.log(serverAcquiredAddress);
displayQrCode(serverAcquiredAddress);
!devEnv && opn(serverAcquiredAddress);
app.locals.fileCount = 0; // Store the number of files, useful for generating new ids
await storage.init();
await storage.clear();
configureApp();
configureSocketServer(server);
});
};
getInterfaceAddress().then((address) => {
createServer(address);
});
function displayQrCode(address) {
const qr_image = qr.imageSync(address, {parse_url: true, size: 1, margin: 3, ec_level: 'H'}),
qr_svg = qr.image(address, { type: 'svg' });
qr_svg.pipe(require('fs').createWriteStream('generated_qr.svg'));
pngStringify(qr_image, (err, pngStr) => {
if (err) throw err;
console.log(pngStr);
});
}
function configureApp() {
route(app);
}
function configureSocketServer(server) {
app.locals.io = require('socket.io').listen(server);
}
// Serve from React's build
app.use("/", express.static(path.join(__dirname, 'client', 'build')));
exports.storage = storage;