Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 133 ยท Getting Started

Running Node: Files, REPL and Flags

Learn every way to run Node.js code - node file.js, the REPL, node -e and -p, shebang scripts, --watch, --env-file, --run, loadEnvFile and exit codes.

Writing code is half the job; the other half is running it. On your computer you launch Node from a terminal, and the command you type decides a lot: which file runs, which arguments it receives, which environment variables it sees, whether it restarts when you save. This lesson tours the ways to start Node and the flags you will use every week.

A note about the examples. Our editor runs your code for you as a file called main.mjs, and it cannot show you an interactive terminal. So the shell commands below are read-only blocks that show what you would type and see on your own machine. Wherever possible we also give a runnable twin: a program that starts a second Node (process.execPath is the path of the running Node binary) with the same flags and prints what happened.

Running a file

Save a program in a file and give it to node:

Terminal
node hello.mjs

Node reads the file, runs it from top to bottom, then keeps running while there is pending work (open servers, timers, unfinished I/O) and exits when there is none. The extension matters: .mjs always means an ES module, .cjs always means CommonJS, and a plain .js file follows the nearest package.json ("type": "module" or the default CommonJS). ES modules and CommonJS cover the details.

Arguments

Everything after the file name goes to your program in process.argv, an array of strings. The first two items are the path of Node and the path of your script; your arguments start at index 2.

Terminal
node greet.mjs Amara --loud

Here is a runnable twin. It writes a small script to disk, then runs it with two arguments in a child Node.

Node.js Reading command-line arguments

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.

slice(2) skips Node and the script path. For real tools with options and help text, Node ships util.parseArgs, covered in CLI tools.

The REPL

Run node with no file and you get the REPL (Read-Eval-Print Loop), an interactive prompt. Type an expression, press Enter, see the result:

TEXT
$ node
> 2 ** 10
1024
> const words = ['node', 'is', 'fun']
undefined
> words.map((w) => w.toUpperCase())
[ 'NODE', 'IS', 'FUN' ]
> .help
> .exit

This session is read-only (our editor has no terminal). The REPL is perfect for trying a method, testing a regular expression or exploring an object. Useful details:

  • _ holds the last result.
  • Press Tab to complete names and see properties.
  • Built-in modules are available without import: type os.platform() or fs.readdirSync('.') directly.
  • Dot-commands control the REPL: .help, .editor (multi-line mode), .save file.js, .load file.js, .exit (or press Ctrl+D).
  • Top-level await works in the REPL.

node -e and node -p: one-liners

-e (evaluate) runs a string of code; -p (print) also prints the value of the last expression. They are great for tiny jobs in shell scripts.

Terminal
node -e "console.log(new Date().getFullYear())"
node -p "process.versions.node"
echo "hello" | node -p "require('fs').readFileSync(0, 'utf8').trim().length"

These ran against your own machine's clock and version, so we do not quote their output. The runnable twin starts a child Node with the same flags on fixed input:

Node.js node -e and node -p

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 -e code can use require even though our own file is an ES module. Code given on the command line is treated as CommonJS unless you add --input-type=module.

Shebang scripts

On Linux and macOS a script can run like a program, without typing node. Start the file with a shebang line and mark it executable:

Terminal
#!/usr/bin/env node
console.log('I run directly!');
Terminal
chmod +x tool.mjs
./tool.mjs

The kernel reads #!/usr/bin/env node, finds node on your PATH and passes the file to it. Node itself ignores the first line when it starts with #!, so the file stays valid JavaScript. This is how npm packages offer command-line tools through the bin field (see CLI tools). Windows ignores shebangs, and npm creates small wrapper files instead.

Node.js A shebang line is just a comment to Node

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.

Watching for changes: --watch

While developing you do not want to stop and restart after each edit. The --watch flag (stable since Node 22) restarts the program whenever the file, or a module it imports, changes:

Terminal
node --watch server.mjs
TEXT
Restarting 'server.mjs'
Completed running 'server.mjs'

This replaces the old nodemon package for most cases. --watch-path=./src watches a specific folder, and --watch-preserve-output keeps old output on screen. Watch mode is a development tool; it is meaningless in our editor, where every run is a fresh process.

Environment variables and --env-file

Programs read settings such as ports and API keys from environment variables, available in process.env as strings (missing ones are undefined). You can set them in the shell:

Terminal
PORT=4000 node server.mjs

Typing them every time is tedious, so keep them in a .env file and let Node load it:

TEXT
PORT=4000
GREETING="Hello from the file"
# comments are allowed
Terminal
node --env-file=.env server.mjs

--env-file is built in (Node 20.6+), so the dotenv package is rarely needed now. You can pass the flag several times; later files override earlier ones. If you prefer to load a file from inside your program, call process.loadEnvFile(), which reads .env by default. It does not override variables already set in the real environment.

Node.js Loading a .env file

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.

Remember that values are always strings: process.env.PORT * 2 works only because JavaScript coerces "4000" to a number. Convert explicitly in real code. Never commit .env files that hold secrets; secrets and config covers safe handling.

package.json scripts and node --run

Projects list their commands in the scripts section of package.json:

JSON
{
  "name": "my-app",
  "type": "module",
  "scripts": {
    "start": "node server.mjs",
    "dev": "node --watch --env-file=.env server.mjs",
    "test": "node --test"
  }
}

You run them with npm (npm run dev, or just npm start and npm test). Node 22+ can run them directly with node --run, which skips npm's startup time:

Terminal
node --run dev

node --run is deliberately simple: it runs the script with your shell and adds node_modules/.bin to the path, but it does not run pre/post hooks. The next example creates a package.json and calls it.

Node.js node --run

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.

Exit codes

When a program ends it reports a number to the operating system: 0 means success, anything else means failure. Shells, CI systems and && chains depend on it. Node exits with 0 when the work runs out; an uncaught exception gives 1. Set your own with process.exitCode, which lets the program finish cleanly, or with process.exit(code), which stops immediately and may cut off pending output or cleanup.

Node.js Reading exit codes

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.

Prefer process.exitCode in most programs: it lets timers close and streams flush. Use process.exit() only when you must stop right now. The process object goes deeper, including signals.

How our editor runs your code

Every Run in these lessons executes this command on a server:

Terminal
node --enable-source-maps --max-old-space-size=256 main.mjs
  • Your code is saved as main.mjs, so it is an ES module: import, export, top-level await and import.meta work, while require, __dirname and __filename do not (use import.meta.dirname and import.meta.filename).
  • If the first line is // cjs, the file is saved as main.cjs and runs as CommonJS. If it is // ts, the file runs as TypeScript with Node's built-in type stripping.
  • --enable-source-maps makes stack traces show original line numbers.
  • You cannot pass other flags to the main process, but a child process can use any flag, as the examples above did.
  • There are limits: about five seconds of run time, 512 MB of memory and 64 KB of output.
Node.js Which file is running?

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.

process.execArgv lists the flags given to Node itself, as opposed to process.argv which lists arguments for your script.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In node greet.mjs Amara, where do you find "Amara"?

    argv[0] is the Node binary, argv[1] the script path, and your own arguments start at index 2.
  2. 2. What is the difference between node -e and node -p?

    Both evaluate a string. -p also prints the result of the final expression, which is handy for one-liners.
  3. 3. Which command loads variables from a .env file without any package?

    --env-file is built into Node 20.6 and later. Inside a program, process.loadEnvFile() does the same job.
  4. 4. A script sets process.exitCode = 2 and then finishes normally. What does the shell see?

    process.exitCode is used as the exit status when the process ends on its own, so the shell sees 2.
  5. 5. Why is process.exit() usually worse than process.exitCode?

    process.exit() ends the process immediately, so buffered writes and timers may never finish.

Summary

  • node file.mjs runs a program; extra words go to process.argv starting at index 2.
  • The REPL (node alone) is for experiments; -e runs a string and -p prints its value.
  • A #!/usr/bin/env node first line lets a script run as a command on Linux and macOS.
  • --watch restarts on changes; --env-file=.env and process.loadEnvFile() load settings; node --run name starts a package.json script.
  • Exit code 0 means success; set others with process.exitCode.
  • Our editor runs main.mjs as an ES module with --enable-source-maps; terminal sessions are shown read-only.

Next: Globals and the console