Now, if I put the workingfile.js in a work folder, and try to call the .env with the same code above, of course it won’t work… I have been trying different combinations to call the file “./.env” “…/.env” “././.env”
the filing structure would look like this
MainFolder
node modules
.env (this is the root)
public> (public folder at the root)
work folder>
work-file.js>> (this is where I want to call the .env and it isn't working. A file inside the work folder located at the root.
app.js
package.json
I think the problem is the .env call because the code works good if I put the work-file.js at the root, and as soon as I put it in a folder, then the code breaks with lack of authorization… which seems to be related with the information from the .env file.
So I tried what you described and it also doesn’t work on my side as well. It seems impossible for scripts located in a subfolder to read a .env file in the root. I tried giving the path option an absolute path like so __dirname + '/work folder/.env', and it also didn’t work. Surprisingly, if I run a JS script in the root folder, I can easily read a .env in a subfolder.
But then I thought, why not create the .env file in the same folder as your script? I tried it and it seems to work fine. In your case, maybe try creating the .env file inside work folder.
Of course this doesn’t solve the exact question you asked, but it’ll help work with the dotenv.
creating the .env inside the work folder? that might work, but I was thinking the .env was always supposed to be located at the root??? I might be mistaken??
I also have other files that need the access to the .env , and I am thinking about put them in different folders so it isn’t too crowded … but then, as soon as I put them in a folder the code breaks… grr…
Yup. I created a folder called test folder in my root folder and put the .env file there. JS scripts in the root and those in the test folder accessed it. But you are definitely run into problems when files not located in the root try to access the .env. Will keep digging around to the dotenv documentation and hit you up if i find anything. I think the issue is getting the path right. I tried console.log(__dirname + ‘path/to the .env’) and the computer gives a funny path with a mixture of ‘/’ and forward slash in the path. Lemme try path.resolve().