javascriptnode.jslocomotivejs

locomotive.js listen to http and https


i have a locomotive.js MVC project , and its listening on http. i want to listen on https , and redirect all http to https.

i cant find the createServer of node.js, the only code i find is: under /lib/node_modules/locomotive/lib/locomotive/cli/server.js

console.log('booting app at %s in %s environment', dir, env);

locomotive.boot(dir, env, function(err, server) {
  if (err) {
     throw err;
  }

  server.listen(port, address, function() {
     var addr = this.address();
     console.log('listening on %s:%d', addr.address, addr.port, addr);
  });
});

changed to :

console.log('booting app at %s in %s environment', dir, env);
var crypto = require('crypto'),
       fs = require("fs");
var privateKey = fs.readFileSync('/privatekey.pem').toString();
var certificate = fs.readFileSync('/certificate.pem').toString();
var https = require('https');
var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

and i am kind of stuck now , any help ?

Thanks !


Solution

  • This is not very well tested, but it seems to work:

      // start.js
      var locomotive  = require('locomotive');
      var app         = new locomotive.Locomotive();
      var http        = require('http');
      var https       = require('https');
      var fs          = require('fs');
    
      app.boot(__dirname, 'development', function(err, server) {
        var options = {
          key : fs.readFileSync('server.key'),
          cert: fs.readFileSync('server.crt')
        };
        https.createServer(options, server).listen(port, address);
      });
    

    There's a couple of issues with it (hardcoded directory name and environment, and it doesn't include the HTTP-redirecting part), but those are minor.