Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't start NodeJS HTTPS server. v0.10.23

Some time ago I tried pretty much the same code on previous version of nodejs and it worked (suppose we have router already)

var https = require('https');
var fs = require("fs");
var crypto = require("crypto");

var private_key = fs.readFileSync("cert/domainname.key").toString();
var cert = fs.readFileSync("cert/domainname.crt").toString();
var options = crypto.createCredentials({
  key: private_key,
  cert: cert
});

var server = https.createServer(options, router);
server.listen(8080);

I got error Missing PFX or certificate + private key. Why is that? I passed both private key and certtificate.

like image 827
Vitalii Korsakov Avatar asked Jun 25 '26 23:06

Vitalii Korsakov


1 Answers

You shouldn't need to use crypto.createCredentials() or .toString() the file contents:

var options = {
    key: fs.readFileSync('cert/domainname.key'),
    cert: fs.readFileSync('cert/domainname.crt')
};

var server = https.createServer(options, router):

https.createServer() expects an options Object, with either a pfx or key and cert, rather than a credentials object created by crypto.createCredentials().

And using .toString() on the Buffers from readFileSync() will attempt to treat the binary as UTF-8 and convert to a UTF-16 String, which may actually cause data loss.


Side note: Unlike require(), fs paths like 'cert/domainname.key' will be relative to the current working directory. To treat them as relative to the current module file, you can combine them with __dirname.

fs.readFileSync(__dirname + '/cert/domainname.key')
like image 107
Jonathan Lonowski Avatar answered Jun 28 '26 18:06

Jonathan Lonowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!