📅  最后修改于: 2023-12-03 15:00:31.821000             🧑  作者: Mango
If you are a programmer, you are likely familiar with node and GitHub. While node is a popular platform for developing server-side applications, GitHub is a widely-used code hosting platform. However, you might not have heard of dotenv before. In this article, we’ll provide a primer on dotenv, and explain how it can be used alongside node and GitHub.
dotenv is a dependency module for node, which can be used for handling environment variables. It loads environment variables from a .env file into process.env, making them globally accessible in your code. dotenv is especially useful for managing sensitive or configurable data, like API keys, database connection strings, or other credentials. By using dotenv, you can keep this sensitive data out of your codebase, making it more secure.
To install dotenv, open your command line, navigate to your project directory (where your package.json is located), and run the following command:
npm install dotenv --save-dev
This will install dotenv as a dependency in your project.
Using dotenv is straightforward. Simply create a .env file in the root directory of your project, and add your environment variables in the following format:
VARIABLE_NAME=value
For example, if you are using an API key for a service called MyService, you would add the following to your .env file:
MY_API_KEY=xxxxxxxxxxx
In your code, you can access the value of this environment variable using the process.env
object, like this:
const apiKey = process.env.MY_API_KEY;
In order to keep your sensitive data secure, you should not commit your .env file to version control (such as GitHub). Instead, you can create a template .env.example file, which contains placeholder values for your variables, and commit that file to your repository. This will allow other developers to see which environment variables are expected, without exposing the actual values.
When a new developer clones your repository, they can copy the .env.example file to a new .env file, and add their own values for the variables. They should never share their .env file with anyone else, and it should not be committed to version control.
By using dotenv, you can ensure that your sensitive data is kept secure, and prevent it from being exposed in your codebase. Combined with node and GitHub, you can create powerful, secure applications that are easy to manage and maintain.