Sitemap

Node.js Fundamentals: Working with Process Object, Command Line & .env Files.

(Node Series Part 3)

In this section, I will share my notes on Process, CLI, and Environment variables.

Process

In Node.js, the process is a global object that provides information about and control over the current Node.js process. It’s part of the Node.js runtime and does not need to be imported.

Think of it as a way for your code to interact with the environment it’s running in — like reading environment variables, exiting the program, or handling signals like Ctrl+C.

Here are some common uses of the process

Command-Line Arguments

Help access command line arguments passed by using process.argv.For example, write this inside a file I have added to index.js

console.log(process.argv); 
node index.js test // here test is a argument 

Here the first one is the directory path, and the second one is the complete file path, which will always be there

Process Control

Exit the Program: To exit the node program manually, u write this in the code process.exit(0)

When your code reaches this line, it will stop the server. Here 0 means success if u pass anything else, it means it will fail with he passed value.

process.exit(0)// 0 means success, any other code means error

Kill the program : Kills another process by PID.

process.kill(pid, [signal])

Abort the Program

process.abort()

Get Environment Variables

console.log(process.env); // All environment variables
console.log(process.env.PATH); // Specific variable (e.g., PATH)
console.log(process.env.NODE_ENV); // Common in (development/production)

Current Working Directory

process.cwd() returns the current working directory of the process,

process.cwd()

But wherever ever u start and start the node process, it will become the current working directory. u can see I am a node-course, no matter what file I access and run, the current working directory path is node-course .

Press enter or click to view image in full size

Process Id

Here u get the process id of the program I am running, server.j,s and to get the process id simply use process.pid

console.log(process.pid); // Useful for logging or killing the process
Press enter or click to view image in full size

Uptime

Tells how much time has elapsed since the server started in seconds

process.uptime()
console.log(`Uptime: ${process.uptime()} seconds`);

Server.js

const http = require('http');
const PORT = 3000;

const server = http.createServer((req, res) => {
// Log incoming requests
console.log(`${req.method} ${req.url}`);

// Dummy endpoint: GET /hello
if (req.method === "GET" && req.url === "/hello") {
console.log(`Uptime: ${process.uptime()} seconds`);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello, world!" }));
return;
}
// Fallback for other endpoints
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});

server.listen(PORT, () => {
console.log(process.pid);
console.log(`🚀 Server running at http://localhost:${PORT}`);
});
Press enter or click to view image in full size

Handle Errors

Here I have shown 4 common errors

exit: Catch normal exits; whenever the program exits, this block will catch it. This happens only when u do this using process.exit(), you can restart the server or do some cleanup.

process.on("exit", (code) => {
console.log(`Process exiting with code ${code}`);
});

uncaughtException: This happens when the application crashes due to any issue . This is one of the priority error handler that shall be there in your code.

process.on("uncaughtException", (err) => {
console.error("Uncaught2 exception:", err);
process.exit(0);
});

Now, here you can write the error inside the file or send mail so that you know the server is down.

Here, process.exit(0) so that we can shut down the server since it has crashed. We do this to close the server gracefully.

SIGTERM: This triggers when you manually close the process. When you kill the process using the pid from the task.

process.on("SIGTERM", () => {
console.log("Caught SIGTERM , closed manually");
process.exit(0);
});

SIGINT: This triggers when you close the server using Ctrl+C command

// Catch Ctrl+C
process.on("SIGINT", () => {
console.log("Caught SIGINT (Ctrl+C)");

process.exit(0);
});

Memory Usage

Here you keep track of memory usage, u can log the memory in file.

process.memoryUsage()
Press enter or click to view image in full size

Command Line Interface(CLI)

Applications to interact with with Operating System. Like your terminal command prompt. It’s a way to chat with the Operating System. The messages are not normal; they are fixed, developer-defined.

  • It’s a concept, not a specific tool.

Examples:

  • Bash
  • Zsh
  • PowerShell
  • CMD (on Windows)

👆🏻 programs that implement / run a command-line interface. Example of CLI commands: ls, cd, pwd.

⚙️ Shell: a program (bash, zsh, fish, PowerShell) that runs inside your terminal; it interprets your commands like ls, cd, echo, etc.

Press enter or click to view image in full size

Some CLI tools are commonly used. These are individual programs that have their own command-line interfaces

  • git → the Git CLI
  • node → the Node.js CLI
  • npm → the npm CLI
  • ls → a CLI to list files

Creating your own cli on node

create a node file, and paste the below code will always be the first line in the file. This tells that this file is a CLI file

#!/use/bin/env node //no space in start

#!/usr/bin/env node

  • #! tells the OS: “Use this program to interpret the script”
  • /usr/bin/env is a command that finds node in your environment’s PATH
  • node is what you want to run the script with (the Node.js interpreter)

I created file cli.js

#!/usr/bin/env node

console.log(process.argv)
console.log("Making a cli tool")

Usually, you need to run using Node like node cli.js

There are multiple ways to create a CLI

  1. Making it executable
ls -la
chmod u+x filename.ext // ext-extension

./filename.ext

Here, I have made the cli.js executable file

2. Symlink

Since you already have the package.json, simply add

 "bin": {
"runboi": "./cli.js" // the path to your file
},

my package.json looks like this now

{
"name": "cource",
"version": "1.0.0",
"author": "shubham gupta",
"type": "commonjs",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"bin": {
"runboi": "./cli.js"
},
"keywords": [],
"license": "ISC",
"description": ""
}

Simply run npm link, make sure the file is executable the first way, and this will create a link in Linux bin that contains all the executable files of the command This tells OS if I run this command, you can find the executable file here

In Windows no need to run npm link; simply run

npm install . 

now u can directly run the command

Press enter or click to view image in full size

Here are the summarized steps to make the file executable

Press enter or click to view image in full size

Let’s implement a real world example like i want to update version whenever the build is done of my project

Get Shubham Gupta’s stories in your inbox

Join Medium for free to get updates from this writer.

firstly simply update the executable file, here i will update the cli.js file

import fs from "fs";

fs.readFile("./package.json", "utf-8", function (err, data) {
if (err) {
console.error("Error reading file:", err);
return;
}

console.log(data);
const newData = data.replace("1.0.0", "1.0.1");

fs.writeFile("./package.json", newData, function (err) {
if (err) {
console.error("Error writing file:", err);
return;
}
console.log("Version updated successfully!");
});
});
Press enter or click to view image in full size

now simply run your command

Press enter or click to view image in full size

Now there are some packages to manage when arguments are passed or we need to take complex arguments,s o to manage those, we have some packages to manage this

Environment Variable

So why do we need the environment?

When developing a website or app, teams need separate workspaces to build and test new features without affecting the live version. Organizations create copies of their databases and servers for each stage (development, testing, production), each requiring different configurations like API keys or database URLs. Environments (managed via tools like .env files) centralize these settings, ensuring security and consistency across teams. This way, developers can experiment safely, testers can validate changes, and users only interact with stable, production-ready code.

environment Is an OS Global Object that can be restricted to Per Terminal, or can be restricted to Per Process.

Just like JS we have local storage , window object, session storage, cookies to store information on a persistent and temporary basis, similarly, env vars are the OS's way of storing common information that can be accessed by any application. (Scope can be configured)

The environment In Node.js refers to the set of variables that are available to a program at runtime.

These variables are stored in the process.env object, which is an object containing key-value pairs of environment variable names and values.

Here’s an example of how to use the process.env object to access environment variables:

// script.js
console.log(process.env.NODE_ENV);

Some common points to remember while creating env variables

Convention is ALL_CAPS_WITH_UNDERSCORES

  1. It’s the POSIX(Portable Operating System Interface) convention for env variables.
  2. It stands out in logs / config
  3. Easy to distinguish from regular code variables
  4. Data Type is always string it always get’s type casted in String.

If you use names like node_env, it might work for you, for the code that you have written, but third-party libraries or different machine might ignore this. Some tools expect NODE_ENV, not node_env.

POSIX (Portable Operating System Interface) is a set of IEEE standards that define compatibility between Unix-like operating systems (Linux, macOS, BSD) and software. It ensures programs can run consistently across different systems by standardizing.

Ways to create environment variables.

Command Specific

No other command, process can access this environment variable.

I have added an env variable in index.js,

console.log(process.env.GOKU)
console.log(process.env.ICHIGO)

we get this as there are no such variables present, so create them

Press enter or click to view image in full size

So now variables are present for that command, which means only at that moment the variable will be available, if u try again, u will get undefined.

Press enter or click to view image in full size
on linux/mac:
ENV_VAR_NAME=value node file.ext

on Windows CMD:
set NODE_ENV=production
node app.js

on Windows Powershell:
$env:NODE_ENV = "production"
node app.js

Session-specific

tabs on the same terminal can access the env variable.

I will access my variable in index.js

console.log(process.env.NODE_ENV)

in the terminal, set the value using the export

console.log(process.env.NODE_ENV)

Then run your index.js file

The variable is available. As soon as I open a new tab terminal and run the same, the value will not be accessible

Press enter or click to view image in full size

You can check it with the following command in the same terminal

 echo $NODE_ENV.
Press enter or click to view image in full size
Windows CMD
set NODE_ENV=production

Windows PowerShell
`$env:NODE_ENV = "production"`

Permanent OS Level

Add this line to the relevant files, and restart the terminal.

Run the following command in your terminal, try one of these

In some case, u might not have permission to edit, simply run

chmod +x filename

Now open in editor mode

vi filename
//in my case
vi ~/.bashrc
Press enter or click to view image in full size

Press i key so that u see insert mode, and now you can add your variable here with export

now press esc key and now press shift + : key and and then type wq

Press enter or click to view image in full size

Now open a new terminal and check

env
Press enter or click to view image in full size

You can now access it from your node project also

Through GUI in Windows:

  1. Open Start → Environment Variables
  2. Under “User variables” or “System variables”, click New
  3. Add your Environment_Variable_Name, and production as the value
  4. Restart your terminal

As you know type of environment variable will always be a string You can check here as a boolean value is assigned, but the type is changed to a string

Process Level

Simply create a file with .env extension in your root folder (a convention so that other developers can easily find it)

I added a username in this file

USER_NAME="ICHIGO"

Now, how do we read the value inside the node project? Install this library

npm install dotenv

now in your index.js

import 'dotenv/config'; // Auto-loads .env file
console.log(process.env.USER_NAME);
Press enter or click to view image in full size

Process Level Prod Standard

We have a different env file for different stages of the project

.env              # default (development)
.env.development # dev-specific
.env.production # production-specific
.env.test # test-specific

Now let’s add some files in our node code, I have added to the file .stage.env and .prod.env

// .prod.env
USER_NAME="ICHIGO"
MODE="PROD"
//.stage.env

USER_NAME="ICHIGO"
MODE="STAGE"

Create a load-env.js file, which will help access the file based on the environment

import { readFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { config } from 'dotenv';
import { cwd } from 'process';

function loadEnvironment() {
const env = process.env.NODE_ENV || 'development';
const envFile = `.${env}.env`;
const envPath = resolve(cwd(), envFile);
console.log(env,envPath)

try {
if (existsSync(envPath)) {
config({ path: envPath });
console.log(`Loaded environment: ${envFile}`);
}

// Fallback to .env
config();
console.warn(`Loaded default .env (could not find: ${envFile})`);

} catch (error) {
console.warn(`Failed to load env: ${error.message}`);
}
}

loadEnvironment();

export { loadEnvironment };

inside index.js

import "./load-env.js"
console.log(process.env.USER_NAME);
console.log(process.env.MODE);

Now run pass the environment in the terminal

NODE_ENV="stage" node index.js
Press enter or click to view image in full size

This usually happened in older versions of Node

Process Level without any library

node `--env-file` `env-file-name`  `file-to-run`

node —env-file .env index.js
node --env-file .stage.env index.js
Press enter or click to view image in full size

As you can see inside the index.js, I have not used any library.

Enterprise Apps

At the enterprise level application, we do not manually do this; we use a third-party library for this, one of which is HashiCorp Vault.

If you’d like to be in the know, subscribe, clap, like and share. Cheers!