Node.js is a popular open-source platform used for building scalable server-side applications in JavaScript. One of the key features of Node.js is its ability to utilize environmental variables to configure various aspects of an application. In this article, we will discuss how to set and read Node.js environmental variables from the Linux bash terminal.
What are Environmental Variables?
In simple terms, environmental variables are values that are set in the environment of a computer or a specific application. These values can be used to configure various settings or provide useful information to an application. For example, an environmental variable may specify the location of a database server, a secret key for authentication, or the path to important files.
Setting Environmental Variables in Bash
In Linux, environmental variables can be set in the terminal using the export command. To set an environmental variable, the syntax is as follows:
export VARIABLE_NAME=value
For example, to set a variable called NODE_ENV to "production", we would run the following command:
export NODE_ENV=production
Reading Environmental Variables in Node.js
Node.js allows us to access environmental variables through the process.env object. To read an environmental variable, we simply use the variable name as a key within the process.env object.
For example, to read our NODE_ENV variable that we set earlier, we would write:
console.log(process.env.NODE_ENV) // Output: production
We can also set a default value for an environmental variable using the || operator. For example:
const DB_USERNAME = process.env.DB_USERNAME || 'root'
This code sets the DB_USERNAME variable to the value of the environmental variable DB_USERNAME, or 'root' if the variable is not set.
Conclusion
Node.js environmental variables provide a powerful way to configure applications with important settings or secrets. Linux bash terminal provides a simple way to set these environmental variables, and Node.js provides an easy way to read and utilize these variables in our applications. By leveraging environmental variables, we can create more modular and easily configurable server-side applications.