Running a File
Save your code in a .js file and run it with the node command.
Syntax
node <filename>.jsFor 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
- Create a file, for example
app.js. - Write your JavaScript inside it.
- Open a terminal in that folder.
- Run
node app.js.
Node executes the file from top to bottom and prints anything you send to console.log.
Example
// app.js
const items = ['bread', 'milk', 'eggs'];
console.log('Shopping list:');
items.forEach((item, i) => {
console.log(`${i + 1}. ${item}`);
});
// Run it: node app.jsWhen 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.
# Create the file
echo "console.log('Running!');" > app.js
# Execute it
node app.jsRun with watch mode
Uses the built-in `--watch` flag (Node 18+) to restart the process automatically when the file changes.
# Node 18+ built-in watch (no nodemon needed)
node --watch server.jsPass CLI arguments to script
Reads a positional argument from `process.argv` -- the first two entries are `node` and the script path.
// args.js
const [,, name = 'World'] = process.argv;
console.log(`Hello, ${name}!`);
// Run: node args.js Alice
// Output: Hello, Alice!
Discussion