Reputation: 397
I have a pretty weird situation here.
1.
When I use this code in my tokens.js
file
const pathToPrivKey = path.join(__dirname, "..", "src/helpers/key/id_rsa_priv.pem");
The error is:
Error: ENOENT: no such file or directory, open 'C:\Users\arpitanand\Desktop\node-app\src\src\helpers\key\id_rsa_priv.pem'
Notice that src
is automatically duplicated in the path string as \src\src\
2. When I use this code in my tokens.js
file:
const pathToPrivKey = path.join(__dirname, "..", "helpers/key/id_rsa_priv.pem");
The error is:
Error: ENOENT: no such file or directory, open 'C:\Users\arpitanand\Desktop\node-app\helpers\key\id_rsa_pub.pem'
Notice here that now both the /src/src/
is absent!
This is my folder structure:
----src
| |
| +---controller
| |
| +---helpers
| | | tokens.js //I am here
| | +---key
| | id_rsa_priv.pem //I want to access this file
| | id_rsa_pub.pem
+---test
deleteUser.js
UPDATE
1.
The output console.log(_dirname)
is:
C:\Users\arpitanand\Desktop\node-app\src\helpers
2. And I have already ran this
const pathToPrivKey = path.join(__dirname, "key/id_rsa_priv.pem");
The result of which is:
Error: ENOENT: no such file or directory, open 'C:\Users\arpitanand\Desktop\node-app\helpers\key\id_rsa_priv.pem'
3. I use the pathToPrivKey
here and only here:
const PRIV_KEY = fs.readFileSync(pathToPrivKey, "utf8");
Upvotes: 1
Views: 69
Reputation: 397
Ok, So I don't really know what was happening with my code before but I tried cleaning the npm cache using npm cache clean --force
along with deleting my node modules
and reinstalling them and it worked!
Upvotes: 1
Reputation: 169338
__dirname
is the directory in which the module resides, not e.g. the working directory of the program.
If you have code in src/helpers/tokens.js
and want to refer to src/helpers/key/id_rsa_priv.pem
,
const keyPath = path.join(__dirname, "key/id_rsa_priv.pem");
is enough.
Upvotes: 2