I have a simple problem. I'm trying to shutdown an expressjs nodejs server so that current requests finish their responses and new requests get rejected altogether. I've wittled down my code to just the bare bones so that it'd be easier to understand:
express = require("express")
http = require("http")
app = express()
app.configure ->
app.set "port", process.env.PORT or 3000
app.use app.router
ran = false
app.get '/testrun', (req, res)->
console.log "received request"
if ran
res.json
shouldnt: 'have gotten here'
else
ran = true
setTimeout ->
res.json
response: 'fail!'
, 8000
console.log 'server closing'
server.close()
setTimeout ->
process.exit()
, 10000
server = http.createServer(app)
server.listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
So essentially, I make two requests. The first one takes 8 seconds, and the server is closed immediately. So any future requests should be rejected. The second request, however, still gets through. Console output:
$> Express server listening on port 3000
received request
server closing
received request
If you could explain what's going on I would appreciate it.
UPDATE:
Per Benjamin's response, I tried the test code he suggested, and it worked as expected. The problem is in the browser. I edited the original server:
express = require("express")
http = require("http")
app = express()
app.configure ->
app.set "port", process.env.PORT or 3000
app.use app.router
ran = false
app.get '/testrun', (req, res)->
console.log "received request"
if ran
res.json
shouldnt: 'have gotten here'
else
ran = true
setTimeout ->
res.json
response: 'fail!'
, 5000
console.log 'server closing' # changes here
server.close ->
console.log 'closed!'
server = http.createServer(app)
server.listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
Note the changes around server.close. When I run the test code Benjamin suggested, you get the expected output:
$>Express server listening on port 3000
received request
server closing
closed!
But when I open two tabs in chrome, request the first, wait a few seconds, then request the second, I get this output:
$>Express server listening on port 3000
received request
server closing
received request
And without the process.exit, the 'closed' callback never gets called. Kind of weird behavior.
Thanks for your help.