Your First Node Program and the REPL
Run a script with node, print with console.log, and play in the interactive REPL
node command, or type code line by line in the REPL and see the answer instantly.
- run a JavaScript file with the
nodecommand, - print messages and values with
console.log, - experiment interactively in the Node REPL and exit it cleanly.
1. Two ways to run JavaScript with Node
Once Node.js is installed, you have two handy tools. Think of them as two doors into the same house:
| Way | How you use it | Best for |
|---|---|---|
| Script file | Save code in app.js, then run node app.js | Real programs you want to keep and run again |
| REPL | Type node with no file name, then type code line by line | Quick tests and trying out one idea |
You will use both all the time. Scripts are for building; the REPL is for exploring.
2. Writing and running your first script
Create a file called hello.js and put one line inside it:
// hello.js
console.log('Hello, Node!');
Now open your terminal in the same folder and run it with the node command, followed by the file name:
$ node hello.js
Hello, Node!
That is it — you just wrote and ran a Node program! The $ is the terminal prompt (you do not type it). You type node hello.js, press Enter, and Node runs every line of the file from top to bottom.
hello.js. Running node hello also works because Node adds the .js for you, but hello.js alone (without node) does nothing — the terminal needs the node command to know it should use Node.