-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstart.js
42 lines (29 loc) · 1.98 KB
/
start.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
'use strict'
const express = require('express')
const {resolve} = require('path')
const pkg = require('./package.json')
const app = express()
//The code below works because `.use` returns `this` which is `app`. So what we want to return in the `module.exports` is `app`, and we can chain on that declaration because each method invokation returns `app` after mutating based on the middleware functions
module.exports = app
.use(express.static(resolve(__dirname, '.', 'public'))) // Serve static files from ../public
.get('/*', (_, res) => res.sendFile(resolve(__dirname, '.', 'index.html'))) // Send index.html for any other requests.
// notice the use of `_` as the first parameter above. This is a pattern for parameters that must exist, but you don't use or reference (or need) in the function body that follows.
if (module === require.main) {
// Start listening only if we're the main module.
/*
https://nodejs.org/api/modules.html#modules_accessing_the_main_module
- This (module === require.main) will be true if run via node foo.js, but false if run by require('./foo')
- If you want to test this, log `require.main` and `module` in this file and also in `api.js`.
* Note how `require.main` logs the same thing in both files, because it is always referencing the "main" import, where we starting running in Node
* In 'start.js', note how `module` is the same as `require.main` because that is the file we start with in our 'package.json' -- `node server/start.js`
* In 'api.js', note how `module` (this specific file - i.e. module) is different from `require.main` because this is NOT the file we started in and `require.main` is the file we started in
~ To help compare these objects, reference each of their `id` attributes
*/
const server = app.listen(
process.env.PORT || 3000,
() => {
console.log(`--- Started HTTP Server for ${pkg.name} ---`)
console.log(`Listening on ${JSON.stringify(server.address())}`)
}
)
}