Skip to content

Your First Node Program and the REPL

Programming Node.js Difficulty 1/5

Beginning of the lesson

Your First Node Program and the REPL

Run a script with node, print with console.log, and play in the interactive REPL

Big idea: Node.js lets you run JavaScript outside the browser, right in your terminal. There are two ways to do it: save your code in a .js file and run it with the node command, or type code line by line in the REPL and see the answer instantly.
By the end you will be able to:
  • run a JavaScript file with the node command,
  • 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:

WayHow you use itBest for
Script fileSave code in app.js, then run node app.jsReal programs you want to keep and run again
REPLType node with no file name, then type code line by lineQuick 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.

The file must really be named 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers