Skip to content

Commit 0a6fe8a

Browse files
committed
Close the server
1 parent adbc111 commit 0a6fe8a

2 files changed

Lines changed: 36 additions & 3 deletions

File tree

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ const app = require('https-localhost')
4141
app.get('/', (req, res) => res.send('Hello World!'))
4242
```
4343

44+
You can close the server with `app.close()`.
45+
Closing the server is an async operation, you can get notified with `app.close(callback)` or `app.close().then(...)`.
46+
4447
---
4548

4649
### License

index.js

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,26 +15,56 @@ const certOptions = {
1515

1616
// run express on 443
1717
const app = express()
18-
https.createServer(certOptions, app).listen(443)
18+
app.server = https.createServer(certOptions, app).listen(443)
19+
// save sockets for fast close
20+
const sockets = []
21+
let nextSocketId = 0
22+
app.server.on('connection', socket => {
23+
const socketId = nextSocketId++
24+
sockets[socketId] = socket
25+
socket.on('close', () => delete sockets[socketId])
26+
})
1927

2028
// gzip compression and minify
2129
app.use(compression())
2230
app.set('json spaces', 0)
2331

2432
// redirect http to https
25-
http.createServer(function (req, res) {
33+
app.http = http.createServer(function (req, res) {
2634
res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url })
2735
res.end()
2836
}).listen(80)
37+
// save sockets for fast close
38+
app.server.on('connection', socket => {
39+
const socketId = nextSocketId++
40+
sockets[socketId] = socket
41+
socket.on('close', () => delete sockets[socketId])
42+
})
2943

3044
// ready
31-
console.info("Server running on port 443.")
45+
if (!process.env.TEST) console.info("Server running on port 443.")
3246

3347
// serve static files, launch as: 'node index.js <static-path>'
3448
if (require.main === module) { // called directly (not through require)
3549
const staticPath = process.argv[2]
3650
app.use(express.static(staticPath || process.cwd()))
3751
}
3852

53+
// close the app
54+
app.close = (callback) => {
55+
const promises = [
56+
new Promise(resolve => app.http.close(resolve)),
57+
new Promise(resolve => app.server.close(resolve))
58+
]
59+
// destroy all opens
60+
for (const socketId in sockets)
61+
sockets[socketId].destroy()
62+
63+
return Promise.all(promises).then(() => {
64+
if (!process.env.TEST) console.info("Server closed.")
65+
if (callback) callback()
66+
})
67+
}
68+
3969
// export as module
4070
module.exports = app

0 commit comments

Comments
 (0)