Cannot open SSL Key File in Node server - ENOENT

The readFileSync function evaluates relative paths to the current working directory of the node executable, which on Heroku is /app, not the dist folder. To access your dist folder as a relative path, you should be using path.resolve:

var path = require('path');
var options = {
  key: fs.readFileSync(path.resolve('dist/ssl/keys/server.key')),
  cert: fs.readFileSync(path.resolve('dist/ssl/keys/server.crt'))
};

Alternatives include:

  • fs.readFileSync(__dirName + '/dist/ssl/keys/server.key')
  • fs.readFileSync(process.cwd() + '/dist/ssl/keys/server.key')
  • fs.readFileSync(path.join(__dirName, 'dist', 'ssl', 'keys', 'server.key'))

But I feel that path.resolve is right blend of concise and robust.


Thinking that app.js inside of /dist/server/ might be scoped to that directory, I copied the ssl directory there.

When you log __dirname in app.js you will get /dist/server.

You stored your ssl directory in /dist/server.

So, your key path is /dist/server/ssl/keys/server.key and your cert path is /dist/server/ssl/keys/server.crt

you code should be:

var options = {
  key: fs.readFileSync(__dirname + '/ssl/keys/server.key'),
  cert: fs.readFileSync(__dirname + '/ssl/keys/server.crt')
};

If you store ssl directory in /dist:

your key path is /dist/ssl/keys/server.key and your cert path is /dist/ssl/keys/server.crt

Now, your code should be:

var options = {
  key: fs.readFileSync(__dirname + '/../ssl/keys/server.key'),
  cert: fs.readFileSync(__dirname + '/../ssl/keys/server.crt')
};

I am using the same on one of my project and it works fine without using path.resolve or path.join. Even the ../ parent directory representation is resolved by fs.readFileSync itself.


You can use the "__dirname" variable to access to the directory path of your app, if you have the app.js next to your dist folder where there is the /ssl/keys it will look like these:

var options = {
  key: fs.readFileSync(__dirname + '/dist/ssl/keys/server.key'),
  cert: fs.readFileSync(__dirname + '/dist/ssl/keys/server.crt')
};

// Setup server
var app = express();
var server = require('https').createServer(options, app);