Running code, the REPL and the CLI

Beginner · 6 min

node file.js, -e and -p, the REPL, --watch instead of nodemon, --env-file instead of dotenv, and node --run for package.json scripts.

Before thisInstalling Node and managing versions

Kelvin Omereshone · 6 min

Running code, the REPL and the CLI

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Kelvin OmereshoneReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `node file.js` runs a script, `node -e` runs a string, `node -p` runs a string and prints the result, and `node` alone opens the REPL. Arguments after the script name are passed to the script, not to Node.
  • The REPL keeps the last result in `_`, supports top-level `await`, and has dot-commands such as `.help`, `.save` and `.load`. It is the fastest place to test a one-line idea.
  • `node --watch app.js` restarts the process when an imported file changes, which replaces `nodemon` for most projects. It was experimental when introduced in Node 18.11 and has been stable since Node 22.
  • `node --env-file=.env app.js` loads variables into `process.env` before your code runs, which replaces `dotenv` for most uses. Flags that Node should interpret go before the script name.
  • `node --run <name>` runs a script from `package.json` without starting npm, so it starts faster. It still puts `node_modules/.bin` on `PATH`, but it does not run `pre` and `post` hooks, and a `--env-file` given to `node --run` itself is not passed on to the script.

Four ways to run JavaScript

You already know node app.js. Node has more entry points than that, and each one is the right tool for a different situation:

node app.js a b         # run a file; process.argv.slice(2) is ['a', 'b']
node -e "console.log(1 + 1)"   # run a string
node -p "[1, 2, 3].map(x => x * 2)"   # run a string and print the result: [ 2, 4, 6 ]
node                    # open the REPL

-p is the one people forget. It is -e with an automatic console.log of the final expression, so node -p "process.version" or node -p "require('os').cpus().length" is a quick way to ask the runtime a question without creating a file. Reading from standard input also works: echo 'console.log("hi")' | node -.

One rule keeps trouble away: flags for Node go before the script name; everything after the script name belongs to your program. node --watch app.js foo turns on watch mode and hands foo to your script. node app.js --watch foo hands both --watch and foo to your script and Node does nothing about watching. The process object shows how those arguments appear in process.argv.

The REPL

Run node with no arguments and you get a read-eval-print loop. It is a scratch pad with the whole standard library loaded:

> 1 + 1
2
> _ * 10
20
> fs.existsSync('/tmp')
true
> await Promise.resolve(7)
7

Three details are worth knowing. _ holds the previous result. The built-in modules (fs, path, os and so on) are available as globals without importing them, which is a REPL convenience and does not carry over to scripts. And top-level await works, so you can try an async API directly. The dot-commands are .help, .save <file> to write your session to disk, .load <file> to run a file inside the session, .editor for multi-line input, and .exit or Ctrl+D to leave.

Use it for testing a regular expression, checking what an API returns, or reading what Buffer.from('é') produces before you write the real code.

–watch: restart on change

Before Node 18.11, the standard answer to “restart my server when I save” was installing nodemon. Now it is a flag:

node --watch server.js

Node tracks the entry file and every file it imports. When any of them changes it restarts the process and prints that it did. With --watch-path=./src you choose directories to watch explicitly. The feature was experimental when the video below was recorded (Node 18.11, October 2022) and has been stable since Node 22, so on any current line there is no experimental warning to worry about.

Watch mode is a restart, not hot module replacement. All in-memory state is lost each time. It is the right default for servers and scripts. For front-end dev servers with module hot reloading, use the bundler’s own tooling; see module bundlers and build tools.

–env-file: configuration without a package

dotenv existed to read a .env file into process.env. Node does it itself:

echo 'PORT=4000' > .env
node --env-file=.env -p "process.env.PORT"   # 4000

Variables from the file are in process.env before the first line of your code runs. A missing file stops Node with an error; --env-file-if-exists=.env carries on without one. You can pass the flag more than once, and later files override earlier ones, which is how you layer .env and .env.local. This is only file loading. Validating the values and keeping secrets out of the repository is covered in configuration and environment variables and in the twelve-factor app.

node –run: scripts without npm

If package.json has "scripts": { "hi": "echo hi from run" }, then node --run hi runs it. Skipping npm’s startup makes it noticeably quicker, which matters for scripts you run hundreds of times a day. It is intentionally minimal. Tested on 26.13.1:

  • Binaries in node_modules/.bin are on PATH, so a script that calls mytool still finds it.
  • A prehi script does not run before hi. There are no lifecycle hooks.
  • Arguments after the script name are forwarded to the script: node --run a -- x y prints args: x y.
  • node --env-file=.env --run start does not make those variables visible to the script. Put the flag inside the script itself instead: "start": "node --env-file=.env server.js".

Stay with npm run when you need hooks, workspace flags or other npm behaviour, as npm scripts and lifecycle hooks explains.

What the video covers

Kelvin Omereshone’s video is a short walkthrough of --watch, introduced in Node 18.11 and 19.0, including, per its description, when not to use it. That is one of four topics here. The REPL, -p, --env-file and --run are covered by the prose above, and James Q Quick’s video under “go deeper” covers --env-file specifically. No transcript was available, and the video predates --watch going stable, so ignore any “experimental” framing in it.

Where this fits

Now that you can run, watch and configure a script, the next lesson looks at what a running script can see about its own process: the process object. For the many other flags Node accepts, node --help and the CLI docs are the reference.

Check yourself

  1. 01What is the difference between `node --watch app.js foo` and `node app.js --watch foo`?

    Flags before the script name belong to Node, so the first one turns on watch mode and passes `foo` to the script. Everything after the script name belongs to the script, so in the second command `--watch` ends up in `process.argv` for your program and Node does not watch anything.

  2. 02In the REPL you type `fs.existsSync('/tmp')` without ever importing `fs`. Why does it work?

    The REPL pre-loads the built-in modules as globals, so `fs`, `path`, `os` and the rest can be used without `require` or `import`. This is a REPL convenience only. In a script you still have to import them.

  3. 03Your app reads `process.env.PORT`. How do you load a `.env` file with no dependencies, and what happens if the file is missing?

    Run `node --env-file=.env app.js`. If `.env` does not exist, Node exits with an error saying the file was not found. Use `--env-file-if-exists=.env` to continue silently when the file is absent.

  4. 04Why might `node --run build` and `npm run build` behave differently?

    `node --run` skips npm entirely. It does not run `prebuild` or `postbuild` hooks, and it is a deliberately minimal runner for the `scripts` field. `npm run` adds hooks, workspace flags and other npm behaviour. If a script relies on those, keep using npm.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark