Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Scripts and Workspaces

Environment Variables and Cross-Platform Scripts

Set and read environment variables in npm scripts, use cross-env, dotenv and node --env-file, avoid shell-specific commands, and write scripts that work on Windows, macOS and Linux.

Scripts run in your operating system's shell, and shells disagree. NODE_ENV=production node app.js works on macOS and Linux but fails in classic Windows cmd.exe; rm -rf dist does not exist there at all. If your team or your users use more than one platform, you need habits that avoid these traps. This lesson covers environment variables first, then portable script techniques.

Environment variables in a nutshell

An environment variable is a named string that a process inherits from its parent. Node reads them from process.env. Typical uses: NODE_ENV (development/production/test), PORT, API URLs and secrets such as tokens.

Node.js Reading process.env safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that environment variables are always strings. PORT=0 is the string "0", which is truthy; DEBUG=false is the string "false", also truthy. Compare against explicit strings.

Setting a variable for one script

JSON
{
  "scripts": {
    "start": "NODE_ENV=production node server.js"
  }
}

That syntax works in sh/bash/zsh, so macOS, Linux and Git Bash. In Windows cmd.exe it does not, and PowerShell uses $env:NODE_ENV="production"; node server.js. Four portable options:

  1. cross-env: "start": "cross-env NODE_ENV=production node server.js" (a tiny dev dependency that sets the variable for any shell).
  2. Node's own flag: node --env-file=.env server.js loads a .env file without extra packages (Node 20.6+). Add --env-file-if-exists=.env.local for optional files.
  3. dotenv: import 'dotenv/config' loads .env from code (an npm package).
  4. Configure npm's shell: npm config set script-shell to a bash path (Windows teams with Git Bash). Fragile, so avoid for libraries.

Loading a .env file in Node

The built-in loader is process.loadEnvFile() and util.parseEnv. This runs on the site because it parses a string, not a real file:

Node.js Parsing .env content with node:util

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Never commit .env files that contain secrets. Add .env to .gitignore, commit a .env.example with fake values, and give real values to servers through your host's secret store.

npm's own variables

npm adds npm_package_* variables (from your package.json) and npm_config_* (from config) to a script's environment. npm_lifecycle_event holds the running script's name. They are visible only when started through the package manager.

Cross-platform habits

The shell differences you meet most often:

Task Unix shell Windows cmd Portable way
Delete a folder rm -rf dist rmdir /s /q dist rimraf dist or node -e / node --eval with fs.rmSync
Copy files cp a b copy a b cpy-cli, shx cp, or a Node script
Make a folder mkdir -p x/y mkdir x\y mkdirp or fs.mkdirSync(..., {recursive: true})
Set a variable A=1 cmd set A=1 && cmd cross-env A=1 cmd
Run in parallel a & b start a concurrently, npm-run-all2
Quotes 'single' double only prefer double quotes escaped for JSON

The most dependable approach is to put non-trivial work into a Node script (.mjs file) and call it from package.json. Node behaves the same everywhere.

Node.js A portable clean-and-build script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Paths deserve the same care: use node:path (join) instead of hard-coding / or \, and fileURLToPath(import.meta.url) for the script's own location.

A checklist before you commit a script

  1. Does it use only node, local binaries and portable commands?
  2. If it sets variables, does it use cross-env or --env-file?
  3. Are quotes valid in JSON (escape inner double quotes or use node -e sparingly)?
  4. Does it exit non-zero on failure and print a clear message?
  5. Is a longer one-liner better as a file in a scripts/ folder?

Workspaces build on scripts too; in Workspaces Basics you will run one script across many packages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does "start": "NODE_ENV=production node app.js" fail on classic Windows cmd?

    That inline syntax belongs to Unix shells; cross-env makes it portable.
  2. 2. What type are all values in process.env?

    Convert explicitly; 'false' is a truthy string.
  3. 3. Which Node feature loads a .env file without extra packages?

    Node 20.6+ supports the --env-file flag.
  4. 4. What is the most reliable way to make complex scripts portable?

    Node code behaves the same on all platforms.

Summary

  • Environment variables are strings read from process.env; validate and convert them.
  • Inline VAR=value cmd is Unix-only; use cross-env or node --env-file.
  • Never commit secrets; share a .env.example.
  • Unix commands like rm, cp and mkdir -p need portable replacements or Node code.
  • Prefer a scripts/*.mjs file over clever one-liners.

Next: Workspaces Basics