ENOENT no such file in Express Endpoint for readFileSync

I'm a little crazy trying to figure this out. I have several certificates that I need to pass to the authentication client from my api; however, the application continues to throw ENOENT exceptions, although the file clearly exists in the same directory (I swayed this to make sure). I am using readFileSync, effectively doing the following:

key: fs.readFileSync('./privateKey.pem'), 

It's strange if I run this on a standalone Node server not as part of the api, the file can be found without problems. Is there any consideration that I don't know about when trying to use readFileSync in such a scenario?

Thanks!

+5
source share
1 answer

In node you need to be very careful with relative file paths. The only place I've ever really used them is with require('./_____') expressions, where ./ means "relative to this file." However, require is a special case because it is a function that node automatically creates per-file, so it knows the path to the current file.

In general, standard functions are not able to recognize the directory containing the script that called the function call, so in almost all cases ./ means relative to the current working directory (the directory you were in when you ran node <scriptname>.js ). The only time this is not the case if your script or the module you are using explicitly calls process.chdir to set the working directory to something else. The correct way to link to files relative to the current script file is to explicitly use the absolute path with __dirname + '/file.js' .

+13
source

Source: https://habr.com/ru/post/1207461/


All Articles