Running a File

Save your code in a .js file and run it with the node command.

Syntaxnode <filename>.js

For anything beyond a quick test, put your code in a file ending in .js and run it with the node command followed by the file name.

Steps

  1. Create a file, for example app.js.
  2. Write your JavaScript inside it.
  3. Open a terminal in that folder.
  4. Run node app.js.

Node executes the file from top to bottom and prints anything you send to console.log.

Example

Example · javascript
// app.js
const items = ['bread', 'milk', 'eggs'];
console.log('Shopping list:');
items.forEach((item, i) => {
  console.log(`${i + 1}. ${item}`);
});
// Run it:  node app.js

When to use it

  • A developer runs `node index.js` locally to verify the server starts correctly before pushing to CI.
  • An automation script is executed via `node sync-db.js` as part of a cron job to migrate database records nightly.
  • A team uses `node --watch server.js` during development to automatically restart the process when source files change.

More examples

Run a basic script

Demonstrates the simplest way to execute a Node.js file from the terminal.

Example · bash
# Create the file
echo "console.log('Running!');" > app.js
# Execute it
node app.js

Run with watch mode

Uses the built-in `--watch` flag (Node 18+) to restart the process automatically when the file changes.

Example · bash
# Node 18+ built-in watch (no nodemon needed)
node --watch server.js

Pass CLI arguments to script

Reads a positional argument from `process.argv` -- the first two entries are `node` and the script path.

Example · js
// args.js
const [,, name = 'World'] = process.argv;
console.log(`Hello, ${name}!`);

// Run: node args.js Alice
// Output: Hello, Alice!

Discussion

  • Be the first to comment on this lesson.