-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
77 lines (65 loc) · 2.17 KB
/
app.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
import express from 'express';
import path from 'path';
import fs from 'fs';
import 'colors';
import cors from 'cors';
import dotenv from 'dotenv';
dotenv.config();
//files
const props = JSON.parse(fs.readFileSync('./props/default.json'));
//props
const consoleTxtColor =
props.consoleTxtColor == null || props.consoleTxtColor === ''
? 'cyan'
: props.consoleTxtColor;
const consoleVarColor =
props.consoleVarColor == null || props.consoleVarColor === ''
? 'green'
: props.consoleVarColor;
const consoleAlertColor =
props.consoleAlertColor == null || props.consoleAlertColor === ''
? 'white'
: props.consoleAlertColor;
const consoleErrorColor =
props.consoleErrorColor == null || props.consoleErrorColor === ''
? 'red'
: props.consoleErrorColor;
//server
const __dirname = path.resolve();
const isDev = process.env.ISDEV === 'true' ? true : false;
const port = isDev ? props.port : process.env.PORT;
const app = express();
//middleware
import handleRequests from './middleware/handleRequests.js';
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(handleRequests);
// making everything in public folder static
if (fs.existsSync('./public'))
app.use('/public', express.static(path.join(__dirname, 'public')));
//routes
fs.readdir('./routes', (err, files) => {
//stopping if there are errors
if (err) return;
// filtering out none js files
files = files.filter((file) => file.substring(file.indexOf('.') === '.js'));
// importing and using files
files.forEach(async (fileName) => {
// handling route name
fileName = fileName.substring(0, fileName.indexOf('.'));
const file = await import(`./routes/${fileName}.js`);
const { routeName } = await import(`./routes/${fileName}.js`);
let routerName;
if (routeName == null) routerName = `/${fileName}`;
else routerName = routeName;
// using file
app.use(routerName, file.default);
});
});
//listening
app.listen(port, () =>
console.log(
'Started Better Express server on port: '[consoleTxtColor] +
`${port}`[consoleVarColor]
)
);