I recently made a small project using the Twitter API and wanted a super simple way to store my local environment variables. Fair warning, my method is a little hack-y, but you can riff on it for your own purposes.
I wasn’t familiar with how to set environment variables in Node, and I didn’t want to pass FOO=BAR every time I ran my script, so I wanted to save them somewhere locally and then ignore the file in git so I didn’t expose my API key to Github, and I’d set it up on my server in the server-appropriate way.
In Node, you can access environmental variables using
require('env.js') because this isn’t wrapped in a module.exports (on purpose), the code is literally executed and thus the variables are added to your environment. To load the environmental variables locally, I check to see if one of the variables exists (really you should check them all) and if it doesn’t, then I
require my env module, because I assume I’m running locally.
This had the great side benefit of making it very obvious when I was deploying to an external server if I’d set my environmental variables on the server correctly, because if they didn’t exist, Node went looking for this module. Learn more about process.env in the Node docs.
I used this method in the recent project I ran over the weekend, saving #talkpay tweets to a MongoDB database. It has about 26k records, if you’d like to do some analysis on it. The code for the search and the database dump are both on Github.