Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot open SSL Key File in Node server - ENOENT

I'm attempting to deploy a project I inherited to heroku using grunt buildcontrol for the first time. Though I am able to build and deploy, on running I get an error:

ENOENT: no such file or directory, open 'ssl/keys/server.key'

Checking the dist directory, indeed there is no ssl directory. Thusly, I've added it to /dist to no avail. Thinking that app.js inside of /dist/server/ might be scoped to that directory, I copied the ssl directory there - again the same issue. Inside of /dist/server/app.js:

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

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

Where is it going to look for the ssl directory if not inside the server folder?

like image 541
Eric H Avatar asked Oct 14 '15 19:10

Eric H


2 Answers

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.

like image 97
heenenee Avatar answered Sep 27 '22 20:09

heenenee


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);
like image 33
AugustoL Avatar answered Sep 27 '22 19:09

AugustoL