I’m attempting to automatically locate a specific file that I have stored in my backend for my tlsFile when connecting to DocumentDB. However, I’m finding this odd behavior where __dirname
suddenly changes if the full path name actually resolves to the path of the file name I want.
(Of course, if this is a bad practice in terms of cybersecurity let me know; this project is fortunately not public.)
const client = new MongoClient(uri, {
tlsCAFile: path.join(__dirname, process.env.TLSCAFILE), //Specify the DocDB; cert
tlsAllowInvalidCertificates: process.env.MODE !== "prod",
tlsAllowInvalidHostnames: process.env.MODE !== "prod",
directConnection: true,
auth: {
username: process.env.MONGODBUSER,
password: process.env.MONGODBPASS
}
});
This results in an ENOENT, as such below:
Error: ENOENT: no such file or directory, open '/relative/path/to/key.pem'
at async open (node:internal/fs/promises:639:25)
at async Object.readFile (node:internal/fs/promises:1246:14)
at async MongoClient._connect (/Users/<REDACTED>/node_modules/lib/mongo_client.js:163:32)
at async MongoClient.connect (/Users/<REDACTED>/node_modules/mongodb/lib/mongo_client.js:142:13)
at async MongoClient.connect (/Users/<REDACTED>/node_modules/mongodb/lib/mongo_client.js:295:16) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/relative/path/to/key.pem' // this does NOT have __dirname
}
Why, when I change the process.env.TLSCAFILE
to a non-existent location, does __dirname
suddenly return?
Once I change process.env.TLSCAFILE
from /relative/path/to/key.pem
to /relative/path/to/keythatdoesntexist.pem
, this of course results in an ENOENT, but note the change in file name below:
Error: ENOENT: no such file or directory, open '/full/path/to/directory/relative/path/to/keythatisntthere.pem'
at async open (node:internal/fs/promises:639:25)
at async Object.readFile (node:internal/fs/promises:1246:14)
at async MongoClient._connect (/Users/<REDACTED>/node_modules/lib/mongo_client.js:163:32)
at async MongoClient.connect (/Users/<REDACTED>/node_modules/mongodb/lib/mongo_client.js:142:13)
at async MongoClient.connect (/Users/<REDACTED>/node_modules/mongodb/lib/mongo_client.js:295:16) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/full/path/to/directory/relative/path/to/keythatisntthere.pem' // this DOES have __dirname
}