This repository has been archived by the owner on Dec 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.js
50 lines (43 loc) · 1.58 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
const express = require('express');
const path = require('path');
const fs = require('fs')
const app = express();
// Serve static files from the React app
app.use(express.static(path.join(__dirname, '/build')));
app.get('/api/accounts', (req, res) => {
// Return them as json
fs.readFile('./accounts/accounts.txt', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
let accounts = JSON.parse(data); //now it an object
let chosenAccount = null;
let flag = false
Object.keys(accounts).forEach(function(account) {
if(!accounts[account] && !flag){
chosenAccount = account
accounts[account] = flag = true
}
});
if(chosenAccount !== null){
let updatedAccounts = JSON.stringify(accounts); //convert it back to json
fs.writeFile('./accounts/accounts.txt', updatedAccounts, 'utf8'); // write it back
console.log(chosenAccount)
res.json({
account: chosenAccount
})
}else{
res.json({
account:'No accounts left'
})
}
}});
});
// The "catchall" handler: for any request that doesn't
// match one above, send back React's index.html file.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+'/build/index.html'));
});
const port = process.env.PORT || 5020;
app.listen(port);
console.log(`Project running on ${port}`);