Skip to main content

How to Run a JavaScript File with Node.js

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Node.js runs JavaScript outside a browser, and the node command runs a file of it. Anything you type after the file's name reaches the program as an argument, which is how small scripts take input from the terminal.

Syntax​

Syntax
node <file> [<arguments>]
PartWhat it does
nodeStarts Node.js.
<file>The JavaScript file to run, such as hello.js, or a path to it.
<arguments>Optional. Words passed to the program, which it reads from process.argv.

The Example​

The example is a one-file program, hello.js, that greets whoever you name on the command line, or the whole world when you name nobody, and says which Node.js version ran it.

Prerequisites​

  • Node.js. Check it with node --version. This guide uses Node.js 26.

Step 1: Write the File​

Make a folder for it:

Terminal
mkdir hello-node
cd hello-node

Then create hello.js there:

hello.js, which takes the name from process.argv[2], falling back to world, and prints a greeting with the Node.js version.

hello.js
const name = process.argv[2] ?? 'world';
console.log(`Hello, ${name}! This is Node.js ${process.version}.`);

process.argv lists the command line: the path to node first, then the path to the file, then your arguments. process.argv[2] is therefore the first argument you type, and ?? 'world' uses world when there's none.

Step 2: Run It​

Terminal
node hello.js
Output
Hello, world! This is Node.js v26.13.1.

Step 3: Pass an Argument​

Terminal
node hello.js Ada
Output
Hello, Ada! This is Node.js v26.13.1.

A zsh terminal where node hello.js prints Hello, world! This is Node.js v26.13.1. and node hello.js Ada prints Hello, Ada!

The commands and the output are the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Running node hello.js from another folderNode.js can't find the filecd into its folder, or give the path: node hello-node/hello.js
Two words as one argument without quotes: node hello.js Ada Lovelaceprocess.argv[2] is only AdaQuote it: node hello.js "Ada Lovelace"

Troubleshooting​

SymptomLikely causeFix
Error: Cannot find module '/…/hello.js'You're in a different folder from the fileCheck with pwd, then cd into the right folder
command not found: nodeNode.js isn't installed, or isn't on your PATHInstall it from nodejs.org and open a new terminal

FAQ​

Can I run code without a file?​

Yes. node -e "console.log(1 + 1)" runs the code in the quotes, and node on its own opens an interactive prompt where you type JavaScript line by line.

How do I stop a program that keeps running?​

Press Ctrl+C.

Conclusion​

node <file> runs a JavaScript file, and the words after the file's name reach the program in process.argv, starting at process.argv[2].

Additional Resources​