I was working on a project recently where I have a .env at the project root and using dotenv as usual. But there were some database migration files that were in a subdirectory that needed to be executed. Obviously I want to use the .env because it contains the database credentials.
In order to use dotenv here, I had to specify the path to the .env:
require('dotenv').config({path: '../.env'})
Now this works great. But an alternative solution to this would be to code in dotenv to recursively look for the .env in parent directories if it kind find one. I believe npm does the same thing, looking for a package.json file. It seems like the code for this would be very easy to implement.
Is this functionality that the developer has considered?
BTW, love <3 this package. I use it with, like every web project. It's the first package I install every time.
@Jakobud I wanted this same kind of functionality, in my case because my .env files are in different relative locations in dev vs prod. See issue #238. We found a pretty simple one-liner pattern to accomplish this without any changes to dotenv.
Still, +1 for having it work this way out-of-the box.
one-liner is the way to go if you want recursive lookup.
usually node db/migrate.js instead of cd db && node migrate.js should use the expected .env file. hard to say without knowing more about your specific setup
@maxbeatty Yeah, so I'm using Knex.js. The way it works is that you run it from the project root, but if your knexfile.js (configuration file) is in a subdirectory, which mine is, then it essentially changes the CWD to that directory instead of the project root. So then it's trying to find the .env in the subdirectory even though you executed it from the root directory. Make sense?
Most helpful comment
@Jakobud I wanted this same kind of functionality, in my case because my .env files are in different relative locations in dev vs prod. See issue #238. We found a pretty simple one-liner pattern to accomplish this without any changes to dotenv.
Still, +1 for having it work this way out-of-the box.