Home / Articles

Node.js Command Reference for Local Development and Production Servers

A scannable command reference covering Node.js version management, package managers, environment setup, debugging, PM2, and zero-downtime Linux deployments.

Publisher: REACTAPP.TOP13 min read3017 words

This article is published in English.

Sources: Node.js Cheatsheet — Essential Commands for Developers and Vibe Coders in 2026

nodejs

AI-assisted coding has reshaped the way projects get built. You describe the outcome you want, an AI assistant generates the code, and within minutes you have something running. Yet there's a moment no assistant can handle for you — when you're staring at a terminal window and need to know the exact command to type.

Maybe a deployment breaks on the remote server. Maybe an install fails halfway through. Maybe environment variables refuse to load, or a process dies without leaving a useful stack trace. In those situations you don't want to dig through pages of documentation — you want a quick lookup you can scan in seconds.

That's the purpose of this reference: a compact guide to Node.js commands for two contexts — working on your local machine, and managing a production server. Each command comes with a brief note on when it's the right tool.

Running Node.js

Start with the basics you should know without thinking twice:

# Run a JavaScript file
node app.js

# Run with an environment variable inline
NODE_ENV=production node app.js

# Open the REPL (Read-Eval-Print Loop) - interactive Node.js shell
node

# Evaluate JavaScript directly from the terminal
node -e "console.log(process.version)"

# Check the active Node.js version
node -v
node --version


# Check the active npm version
npm -v

Useful CLI Flags

# Watch mode — auto-restart when files change (Node.js 18+, no nodemon needed)
node --watch app.js

# Enable ES Modules
node --input-type=module app.js

# Increase memory limit for heavy applications
node --max-old-space-size=4096 app.js

# Show longer stack traces
node --stack-trace-limit=50 app.js

# Inspect mode for debugging with Chrome DevTools
node --inspect app.js
node --inspect-brk app.js  # Pause at first line until debugger connects

Node.js Version Management — NVM

For anyone juggling several projects that each expect a different Node.js version, nvm (Node Version Manager) becomes a necessity rather than a convenience.

# Install a specific Node.js version
nvm install 22
nvm install 20.11.0     # Exact version
nvm install --lts       # Latest LTS

# Switch versions
nvm use 22
nvm use --lts

# Set a default version
nvm alias default 22

# List all installed versions
nvm ls

# List available remote versions
nvm ls-remote --lts

# Use the version specified in .nvmrc
nvm use

# Create .nvmrc - lock the Node.js version for this project
echo "22" > .nvmrc

Package Managers — npm, yarn, and pnpm

Picking a package manager is more than a stylistic preference — each option comes with genuine trade-offs.

Heading into 2026, pnpm has become the sensible default for most teams. It installs quickly, uses disk space efficiently, avoids the phantom dependency problem, and offers the strongest monorepo tooling. Tooling support has caught up too — frameworks such as Next.js, Nuxt, and SvelteKit all run cleanly on pnpm.

Still, which one fits best depends on your situation:

  • npm — bundled with Node.js by default, works everywhere, a dependable pick for solo projects and open-source packages
  • yarn — shines in large enterprise-scale monorepos, particularly when paired with Plug'n'Play (PnP)
  • pnpm — the quickest and most storage-efficient option, and the go-to for production setups and monorepos in 2026

Core Commands — All Three Package Managers Side by Side

# Install all dependencies from package.json
npm install
yarn install
pnpm install

# Add a new package
npm install express
yarn add express
pnpm add express

# Add as a devDependency
npm install -D typescript
yarn add -D typescript
pnpm add -D typescript

# Remove a package
npm uninstall express
yarn remove express
pnpm remove express

# Update packages
npm update
yarn upgrade
pnpm update

# Update to latest (beyond semver range in package.json)
npm install express@latest
yarn add express@latest
pnpm add express@latest

# Install without modifying the lockfile - required in CI/CD
npm ci
yarn install --frozen-lockfile
pnpm install --frozen-lockfile

# Run a script from package.json
npm run build
yarn build
pnpm build

# Run a package executable without installing globally
npx create-next-app
yarn dlx create-next-app
pnpm dlx create-next-app

package.json — The Parts You Need Most

{
  "name": "my-app",
  "version": "1.0.0",
  "engines": {
    "node": ">=20.0.0",
    "npm": ">=10.0.0"
  },
  "scripts": {
    "dev": "node --watch src/index.js",
    "start": "node src/index.js",
    "build": "tsc -p tsconfig.json",
    "test": "node --test",
    "lint": "eslint src/",
    "format": "prettier --write src/"
  },
  "dependencies": {},
  "devDependencies": {},
  "type": "module"
}

Audit and Security

# Check for vulnerabilities in dependencies
npm audit
yarn audit
pnpm audit

# Auto-fix vulnerabilities where possible
npm audit fix
yarn audit --fix
pnpm audit --fix

# List all installed packages (including nested)
npm list
npm list --depth=0    # Top-level only

# Check for outdated packages
npm outdated
yarn outdated
pnpm outdated

Environment Variables

Environment variables let you keep configuration separate between development and production. Avoid hardcoding secrets like API keys or database URLs inside your source files.

# Create a .env file
cat > .env << EOF
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://localhost:5432/mydb
JWT_SECRET=your-secret-key
EOF

# Make sure .env never enters version control
echo ".env"            >> .gitignore
echo ".env.local"      >> .gitignore
echo ".env.production" >> .gitignore

# Create .env.example as a template for your team
cp .env .env.example

# Then remove the sensitive values from .env.example

Inside your Node.js code:

// Node.js 20.6+ — load .env without any extra package
// Run with: node --env-file=.env app.js

// Or use dotenv for more flexibility
import 'dotenv/config';
const port    = process.env.PORT         || 3000;
const dbUrl   = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV     || 'development';

// Validate required env vars at startup - fail fast
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
    if (!process.env[key]) {
        console.error(`Missing required environment variable: ${key}`);
        process.exit(1);
    }
}

Module System — CommonJS vs ES Modules

Node.js still supports two module formats, but new projects should default to ES Modules, since it's the modern standard shared with browsers.

// CommonJS (CJS) — the legacy format, .js or .cjs files
const fs      = require('fs');
const path    = require('path');
const express = require('express');

module.exports = { myFunction };
module.exports.default = MyClass;

// ES Modules (ESM) - the modern format, .mjs or .js with "type":"module"
import fs      from 'fs';
import path    from 'path';
import express from 'express';
import { readFile, writeFile } from 'fs/promises';
export function myFunction() {}
export default class MyClass {}

// Dynamic import - for lazy loading
const module = await import('./heavy-module.js');

File System — The Operations You'll Use Most

import { readFile, writeFile, appendFile,
         mkdir, rm, stat, readdir,
         copyFile, rename } from 'fs/promises';
import { existsSync }       from 'fs';
import path                 from 'path';

// Read a file
const content = await readFile('data.txt', 'utf-8');
const json    = JSON.parse(await readFile('config.json', 'utf-8'));

// Write a file
await writeFile('output.txt', 'Hello World', 'utf-8');
await writeFile('data.json', JSON.stringify(data, null, 2));

// Append to an existing file
await appendFile('log.txt', `${new Date().toISOString()} - event\n`);

// Create a directory (including missing parents)
await mkdir('logs/2026/06', { recursive: true });

// Delete a file or directory
await rm('temp-file.txt');
await rm('dist/', { recursive: true, force: true });

// Check if a file or directory exists
if (existsSync('config.json')) {
    // file exists
}

// Get file metadata
const info = await stat('app.js');
console.log(info.size);           // size in bytes
console.log(info.isDirectory());
console.log(info.mtime);          // last modified time

// Read directory contents
const files   = await readdir('./src');
const jsFiles = files.filter(f => f.endsWith('.js'));

// Path helpers - always use path.join, never string concatenation
const filePath = path.join(__dirname, 'public', 'index.html');
const ext      = path.extname('script.js');       // '.js'
const base     = path.basename('/src/app.js');    // 'app.js'
const dir      = path.dirname('/src/app.js');     // '/src'

HTTP Server — Built-in, No Framework Required

import { createServer }     from 'http';
import { createReadStream } from 'fs';

const server = createServer(async (req, res) => {
    const url    = new URL(req.url, `http://${req.headers.host}`);
    const method = req.method;

    // Simple routing
    if (url.pathname === '/' && method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>Hello World</h1>');
        return;
    }

    if (url.pathname === '/api/health' && method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ status: 'ok', timestamp: new Date() }));
        return;
    }

    // Read body from a POST request
    if (method === 'POST') {
        let body = '';
        for await (const chunk of req) {
            body += chunk;
        }
        const data = JSON.parse(body);
        // process data...
    }

    // 404
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Not Found' }));
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Process Management

// Graceful shutdown — close connections before the process exits
process.on('SIGTERM', async () => {
    console.log('SIGTERM received, shutting down...');
    await db.disconnect();
    server.close(() => {
        console.log('Server closed');
        process.exit(0);
    });
});

process.on('SIGINT', async () => {
    // Ctrl+C in terminal
    await cleanup();
    process.exit(0);
});

// Catch unhandled errors
process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err);
    process.exit(1); // Must exit - process state is now unreliable
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection:', reason);
    process.exit(1);
});

// Process information
console.log(process.pid);           // Process ID
console.log(process.env.NODE_ENV);  // Environment
console.log(process.argv);          // CLI arguments
console.log(process.cwd());         // Current working directory
console.log(process.memoryUsage()); // Memory usage

Debugging

# Inspect mode — open chrome://inspect in your browser
node --inspect app.js

# Pause at the first line until the debugger connects
node --inspect-brk app.js

# Enable verbose logging for specific modules
NODE_DEBUG=http,net node app.js

# CPU profiling
node --prof app.js
node --prof-process isolate-*.log > processed.txt

# Memory leak detection
node --expose-gc --inspect app.js

In your code:

// util.debuglog — only outputs when the DEBUG env var is set
import { debuglog } from 'util';
const debug = debuglog('myapp');

debug('This only appears when: NODE_DEBUG=myapp node app.js');

// Simple timing
console.time('database-query');
await db.query('SELECT * FROM users');
console.timeEnd('database-query');

// Output: database-query: 23.456ms

PM2 — Process Manager for Production

PM2 is the go-to tool for running Node.js in production. It restarts your app automatically after crashes or server reboots, and can scale across CPU cores with barely any setup.

# Install PM2 globally
npm install -g pm2

# Start an application
pm2 start app.js
pm2 start app.js --name "my-api"

# Start in cluster mode - uses all available CPU cores
pm2 start app.js -i max   # Automatically matches CPU core count
pm2 start app.js -i 4     # Exactly 4 instances

# View status of all applications
pm2 list
pm2 status

# Real-time monitoring (CPU, memory, logs)
pm2 monit

# View logs
pm2 logs
pm2 logs my-api
pm2 logs --lines 100

# Restart, reload, stop, delete
pm2 restart my-api
pm2 reload my-api    # Zero-downtime reload (cluster mode only)
pm2 stop my-api
pm2 delete my-api

# Auto-restart on server reboot
pm2 startup          # Generates the systemd command - follow the output
pm2 save             # Saves the current process list

# Configuration file
// ecosystem.config.js
export default {
    apps: [{
        name:               'my-api',
        script:             'src/index.js',
        instances:          'max',
        exec_mode:          'cluster',
        watch:              false,
        max_memory_restart: '500M',
        env: {
            NODE_ENV: 'development',
            PORT:     3000,
        },
        env_production: {
            NODE_ENV: 'production',
            PORT:     8080,
        },
        error_file:      'logs/err.log',
        out_file:        'logs/out.log',
        log_date_format: 'YYYY-MM-DD HH:mm:ss',
    }]
};
# Start from the config file
pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env production

Deploying to a Linux Server

Here's the sequence to follow when setting up Node.js on a VPS or Linux box for the first time.

# 1. Update the system
sudo apt update && sudo apt upgrade -y

# 2. Install Node.js via NodeSource (latest LTS)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs

# Or install via nvm for easier version management
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts

# 3. Verify the installation
node -v
npm -v

# 4. Install PM2 globally
npm install -g pm2

# 5. Clone and set up the project
git clone https://github.com/username/my-app.git
cd my-app

# 6. Install production dependencies only
npm ci --omit=dev

# or with pnpm
pnpm install --prod --frozen-lockfile

# 7. Create the production .env
nano .env

# 8. Start with PM2
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup   # Follow the printed instructions

Updating a Deployment Without Downtime

# Pull the latest code
git pull origin main

# Install any new dependencies
npm ci --omit=dev

# Build if needed
npm run build

# Zero-downtime reload (cluster mode only)
pm2 reload my-api

# Or a standard restart
pm2 restart my-api

Linux Commands You'll Actually Use During Node.js Maintenance

# Check what's running on a specific port
lsof -i :3000
sudo netstat -tlnp | grep :3000
sudo ss -tlnp | grep :3000

# Kill whatever is on a port
kill $(lsof -t -i:3000)

# Or forcefully
kill -9 $(lsof -t -i:3000)

# Real-time resource monitoring
htop                   # Interactive (install with: apt install htop)
top                    # Built-in alternative

# Disk usage
df -h                  # Per partition
du -sh node_modules/   # Size of a specific directory
du -sh *               # Size of everything in the current directory

# Follow logs in real time
journalctl -u pm2-root -f   # PM2 logs via systemd
tail -f /var/log/syslog     # System log
tail -f logs/err.log        # Your application error log

# Memory overview
free -h

# Active network connections
ss -s

# Find all running Node.js processes
ps aux | grep node

# Find files by name or age
find . -name "*.log" -mtime +7   # .log files older than 7 days
find . -name "*.env"             # Any .env files

# Clean up old logs
find ./logs -name "*.log" -mtime +30 -delete

# Archive a folder for backup
tar -czf backup-$(date +%Y%m%d).tar.gz dist/ .env

# Transfer files to/from a server
scp -r ./dist user@server:/var/www/my-app/
rsync -avz ./dist/ user@server:/var/www/my-app/dist/

.npmrc and .nvmrc — Two Small Files That Matter

These two configuration files may look trivial, but they matter a lot once you're working with a team.

# .nvmrc — pin the Node.js version for this project
# Place at the project root
echo "22" > .nvmrc

# Everyone on the team just runs:
nvm use
# NVM automatically reads the version from .nvmrc
# .npmrc — npm/pnpm configuration for this project
# Place at the project root

# Save exact versions (no ^ or ~ prefix)
save-exact=true

# Set registry (if using a private registry)
registry=https://registry.npmjs.org/

# For pnpm - allow hoisting if a package requires it
# shamefully-hoist=true
# For pnpm - set the node linker
# node-linker=hoisted

Testing — Node.js Built-in Test Runner

Since Node.js 20, a test runner ships with the runtime itself. For basic test suites, you can skip installing Jest or Mocha entirely.

// test/app.test.js
import { test, describe, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';

describe('Calculator', () => {
    test('addition works correctly', () => {
        assert.equal(1 + 1, 2);
    });

    test('throws on division by zero', () => {
        assert.throws(
            () => divide(10, 0),
            { message: 'Cannot divide by zero' }
        );
    });

    test('async operation resolves correctly', async () => {
        const result = await fetchUser(1);
        assert.equal(result.id, 1);
        assert.ok(result.name);
    });
});
# Run all tests
node --test

# Run a specific test file
node --test test/app.test.js

# Watch mode - re-run on file changes
node --test --watch

# With coverage (Node.js 22+)
node --test --experimental-test-coverage

Pre-Production Checklist

Go through this list before pushing your Node.js app live:

  • NODE_ENV=production is set — this turns on performance optimizations in Express and other libraries
  • Every environment variable your app needs exists on the server itself, not only in your local .env
  • You're running npm ci --omit=dev rather than npm install, so only production dependencies get installed
  • The lockfile (package-lock.json or pnpm-lock.yaml) is checked into git — skipping this can let CI/CD resolve different dependency versions than what you tested
  • Graceful shutdown logic is in place, with SIGTERM and SIGINT both handled correctly
  • Error monitoring is wired up — unhandledRejection and uncaughtException events get logged and trigger alerts
  • PM2 startup has been configured so the app comes back automatically after a server reboot
  • Rate limiting is active to keep your API safe from abuse
  • A health check endpoint is exposed, since load balancers and uptime monitors depend on it

Closing Thoughts

There's no need to memorize everything in this cheatsheet in one sitting. Bookmark it, come back whenever a command slips your mind, and over time the workflow will stick without effort.

AI tools are great at generating code and scaffolding whole projects during this vibe coding phase we're in — but when you're facing a broken production server in the middle of the night, what actually helps is knowing your tools cold. Not trial and error. Not panic.

Focus first on the parts you'll touch constantly: package managers, environment variables, and PM2. Everything else will fall into place as you need it.