murvinlai murvinlai - 4 months ago 28
Node.js Question

How to create an HTTPS server in Node.js?

Given an SSL key and certificate, how does one create an HTTPS service?

Answer

I found following example. It is a few months old, but it might be good:

http://www.silassewell.com/blog/2010/06/03/node-js-https-ssl-server-example/

Directly from that source:

const crypto = require('crypto'),
  fs = require("fs"),
  http = require("http");

var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();

var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

var handler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
};

var server = http.createServer();
server.setSecure(credentials);
server.addListener("request", handler);
server.listen(8000);