Domanda


This is a 2 part question,

Part 1, I have an app that uses express, and I am trying to have zero-downtime deploys. My question is can I start the server and then add my config? Like So:

var app = require("express")

var hasInited = false;

app.use(function(req,res,next){
    while(!hasInited){}
})

var server = require("http").createServer(app)
server.listen(8080);

// Add calls to app.use, app.get, app.post, etc. here...

hasInited = true;

Part 2, In addition to this, is there a way that at the bottom I can remove the middleware from the stack? like app.removeMiddlewareAtIndex(0)?

È stato utile?

Soluzione 2

Sorry To Answer my own question, I wrote my own little library, whenjs, then I came up with this:

// listen.js
var http = require("http")
var when = require("whenjs")
module.exports.init = function(app){
    module.__app = app;
    module.__appIsReady = false;
    var http = http.createServer(function(req,res){
        if(module.__appIsReady){
            module.__app(req, res)
        } else {
            when(function(){ return module.__appIsReady; }, function() {
                module.__app(req, res)
            })
        }
    })
}

module.exports.ready = function(){
    module.__appIsReady = true;
}


// server.js
var listen = require("./listen");
var app = require("express")();
listen.init(app);

// Build The App Here

listen.ready();

I was already having a https and http server, so this makes almost the same amount of sense.

But robertklep had a really great solution too, I just implemented this one first.

Altri suggerimenti

Instead of using a busy wait loop, you could try something like this:

var EventEmitter = require('events').EventEmitter;
var guard        = new EventEmitter();

...

var hasInited    = false;
app.use(function(req, res, next) {
  if (hasInited)
    return next();
  guard.once('hasInited', function() {
    hasInited = true;
    next();
  });
});

...
// when everything is ready:
guard.emit('hasInited');

The overhead of the extra middleware isn't such that I would remove it from the middleware chain (which can be done, but only with a bit of a hack).

But perhaps pm2 is something worth considering though.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top