Yalamber Yalamber - 2 months ago 9x
Node.js Question

Synchronous file read with https in node.js server

I have seen some examples where we can create an Node.js HTTPS server with the code below:

var https = require('https');

key: fs.readFileSync('/path/to/something.key'),
cert: fs.readFileSync('/path/to/something.crt'),
}, app).listen(443);

Is it required here to use
? Will it delay the request for each user until the key and certificate is read? A bit confused about synchronous and asynchronous on this context.


It isn't required to use synchronous reads when creating a HTTP server instance, it's just that it's more convenient, and the files only need to be read once, which is when the server instance is created.

For example, you could also do the following, but it's rather pointless to do so and would make your code less readable:

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

fs.readFile('/path/to/something.key', function(err, key) {
  fs.readFile('/path/to/something.cert', function(err, cert) {
      key: key,
      cert: cert
    }, app).listen(443);

Where you need to watch how things are handled are within the HTTP request handler, which is the function that is run each time the server receives a request. If you were to block the server like so:

https.createServer(function(req, res) {
  // block the thread with something synchronous

One request would be received, and the server wouldn't accept any requests until the blocking operation had completed.