Node.js Hello World

Summary: in this tutorial, you will learn how to build and run the Node.js Hello World program.

Building the Node.js Hello World program

Step 1. Open your terminal and create a new directory called hello-world:

mkdir hello-worldCode language: JavaScript (javascript)

Step 2. Navigate to the project directory:

cd hello-worldCode language: JavaScript (javascript)

Step 3. Create a new file within the project directory named index.js. The index.js file will be the program’s entry point. Please note that you can use any name, such as main.js or server.js.

Step 4. Add the following code to the index. js file:

console.log('Hello, World!');Code language: JavaScript (javascript)

In the index.js file, we output the message 'Hello, World!' to the console.

Step 5. Run the index.js file by executing the following command in the terminal:

node index.jsCode language: JavaScript (javascript)

You should see the following output:

Hello, World!Code language: JavaScript (javascript)

If you see an error instead, the Node.js may not be installed properly on your system.

Adding variables

Step 1. Modify the code in the index.js file to the following:

const firstName = 'John';
console.log(`Hello, ${firstName}!`);Code language: JavaScript (javascript)

How it works.

First, declares a constant firstName and initialize its value to 'John':

const firstName = 'John';Code language: JavaScript (javascript)

Second, embed the value of firstName into a string using a template literal:

`Hello, ${firstName}!`Code language: JavaScript (javascript)

Third, display the message to the console:

console.log(`Hello, ${firstName}!`);Code language: JavaScript (javascript)

Step 2. Open the terminal and run the index.js file:

node index.jsCode language: JavaScript (javascript)

You’ll see the following output:

Hello, John!Code language: JavaScript (javascript)

Using the –watch flag

Whenever you change the code, you need to run the command node index.js to execute the program. This isn’t productive because you have to switch between the code editor and the terminal every time.

To automatically rerun the Node.js program whenever the code changes, you can use the --watch flag as follows:

node --watch index.jsCode language: JavaScript (javascript)

Now, the terminal will automatically rerun index.js whenever you change the code.

Please note that --watch flag has been available since Node.js 18.11.0.

Summary

  • Use the console.log to output a message to the console.
  • Run the command node index.js to execute the code in the index.js file.
  • Use the --watch flag to automatically rerun the Node.js program whenever the code changes.
Was this tutorial helpful ?