Node.js First Program

Chapter 3 18 mins

Learning outcomes:

  1. Creating a workspace in VS Code
  2. Writing your first Node.js program
  3. Running the program
  4. VS Code tasks for easier execution


So in the last chapter, Node.js Setup, we got familiar with the installation process of Node.js on Windows and got to see Node's REPL environment for executing JavaScript code in situ in the terminal via the node command.

If you've not gone through the chapter, we recommend you to do so before proceeding with this one as it's crucially important to have Node.js set up correctly on your computer.

In this chapter, we shall write our very first program for Node.js, execute it using the node command, get a very quick and brief overview of the architecture of Node.js for program execution, and then finally leverage a great feature of VS Code, tasks, in order to ease the process of launching the node executable for executing a given JavaScript program.

This chapter is the cornerstone to making sure that your future trek of learning Node.js is simple and smooth because it focuses on the most important aspect of your Node journey — your development environment.

With the correct configuration of the development environment, development becomes smooth and seamless, both of which are necessary for reducing the general friction one typically has of coding and getting things done.

So without further ado, let's get learning...

Creating a workspace in VS Code

Today's world is filled with a hype of VS Code, and it's highly likely that you already know of it.

Do you? Well, even if you don't, rest assured, for with this course you'll get to set up a Node.js development environment using VS Code.

Starting with the very first thing, create a directory on your system, wherever you find convenient, and name it learning-node. This directory will contain all the learning material that we'll create throughout the rest of this course.

Next up, we'll load this directory in VS Code as a workspace so that we are within the directory all the time while in VS Code, able to easily add/create/update files in it. A workspace in VS Code could be thought of as a project, containing individual files and directories inside of it.

To learn more how to load a directory, in this case learning-node, in VS Code as a workspace, refer to Workspaces in VS Code and How to Set Up and Customize Them?

Once you've set up the workspace, here's how your VS Code setup will look:

learning-node directory loaded in VS Code as a workspace
learning-node directory loaded in VS Code as a workspace

The learning-node directory is shown in the Explorer menu at the left-side bar, currently empty because there is simply nothing in the directory itself.

From this point on, everything we create in VS Code will be within this directory, and thus, depicted back in the Explorer menu.

Your first Node.js program

Behold. It's now time to write your first program in Node. Excited?

Following the typical roadmap of learning a language, where after installation and then setup of the development environment, one immediately goes on to write the first 'Hello World' program, we'll do the same in this section.

But you know what, you're already familiar with the syntax and semantics of how to create your first program to be ultimately executed in Node; your time won't be wasted in understanding the underlying language.

"How," you ask? Well, Node uses JavaScript, remember? So your first program in Node is merely a JavaScript program, and it's 100% likely that you already know JavaScript.

And fortunately, as we shall explore later on in this chapter, and in more detail later on in this course, some popular APIs in JavaScript on the browser, such as printing something to the console, are replicated in the Node runtime.

This has been done intentionally by the Node.js team so as to keep consistency with the browser and thus reduce the learning curve of getting up and running in Node.js.

Lots of talking, let's get to the program now.

We'll log the text 'Hello world!' from our Node.js program.

Nothing such as a Node.js program!

Whenever we use the term 'Node.js program', we actually mean a 'JavaScript program executed using Node.js'.

It's important to remember that there's precisely nothing such as a Node.js program — it's always a JavaScript program executed using the Node.js runtime environment.

However, the term 'Node.js program' obviously allows us to talk succinctly of a JavaScript program executed in the Node runtime.

Create a new file in your learning-node VS Code workspace and name it hello.js, as shown below:

hello.js file in the learning-node workspace
hello.js file in the learning-node workspace

Write the following code in it:

console.log('Hello world!')

And that's it!

The same console.log() that almost every single JavaScript developer is aware of from the browser arena has its lobbying in Node as well (perhaps because console.log() is very influential).

In the browser, console.log() logs a value to the developer's console whereas in Node, console.log() logs a value to the terminal window. And that makes perfect sense with the name of the method, console.log(): "log this thing to the console", where console just represents the terminal.

Alright, with the code created, it's now time to run it.

Running the program

Given that you installed Node.js just as per the steps defined in the previous chapter, Node.js Setup, you should have node available as a global command on your computer.

To quickly check whether this is the case, enter the following command:

.../learning-node>node -v v20.11.1

We saw this command back in the Node.js Setup chapter; it returns back the version of the Node.js runtime. If this command fails on your end, you should review the chapter.

At this point, assuming that node is installed on your computer correctly, go on and enter the following command to run the hello.js file we created above.

.../learning-node>node hello.js

The path to the file to execute follows the node command.

Press Enter and witness the outcome of years of evolution to get to a point where JavaScript is finally made and considered capable enough to power a server — Hello world! It's Node.js.

.../learning-node>node hello.js Hello world!

As you can see, running a Node program is quite simple. There's no compilation step involved (because we're using the JIT-compiling V8 engine which doesn't have a precompilation step). It's just our program and the node command, that's it.

It's important to take note of how we referred to the hello.js file in the command above. That is, because we were in the same directory containing the file hello.js while invoking node, we were able to refer to it as hello.js, without a directory prefix.

Let's say our JavaScript file was in the parent directory of the current working directory (the one where we are in the terminal). Then we would've had to write the following, utilizing the well-known .. symbol to denote the parent directory, as follows:

.../learning-node>node ../hello.js

What's given here is commonly referred to as a relative path as it's relative to the current working directory (learning-node in our case).

Even hello.js, in the node hello.js command that we saw earlier, was a relative path, just not with a directory prefix to begin with.

But we can easily do so using the . symbol which denotes the current directory. Therefore, hello.js can equivalently be expressed as ./hello.js:

.../learning-node>node ./hello.js

Quite simple isn't it?

So that's how we run a Node.js program — the node command followed by the path to the file we wish to execute. Straight and sound.

If we change the file's code, we have to go to the terminal again, rewrite the entire command, and then wait for the file to execute again. Not lengthy but not quick either.

Let's do this now:

console.log('Changing things');
console.log(1 + 2);
.../learning-node>node hello.js Changing things 3

But can we make this re-execution process quicker?

Can we get a keystroke to automate the entry of the node command in the terminal?

Well, it turns out yes, since we're using one of the most customizable editor software of the era, VS Code. Let's set this up now.

VS Code tasks for easier execution

Using an amazing feature of VS Code, dubbed as tasks, we can get it to execute certain commands in the terminal by choosing from a defined set of choices.

Furthermore, leveraging task variables, we can even make these commands dynamic and have them be generated at runtime by VS Code.

One example of a task variable is file (written as ${file} in task commands as we shall see shortly below), which contains the complete path to the current file open in the editor window.

We can use this file variable to run the Node.js file in the editor by using a task (which we'll create below) together with this task variable.

But we won't stop at just creating a task. We'll configure VS Code to automatically run this task when a particular set of keys is hit.

It's VS Code task time.

  1. Select 'Configure Tasks'

    On the top menu bar, select the Terminal option. Then from the dropdown, select the option Configure Tasks...

    Configure tasks option under Terminal menu in VS Code
    'Configure tasks' option under Terminal menu
  2. Create a tasks.json file

    This will open up a small box asking you to select the task to configure.

    Configure tasks menu in VS Code
    'Configure tasks' menu in VS Code

    By default, the option Create tasks.json file from template is highlighted. Press Enter to select it.

    After this, another box opens up asking for the kind of task template to create. From the dropdown, navigate to the option Others and select it:

    This should create a tasks.json file inside the .vscode directory right inside the workspace.

  3. Edit the tasks.json file

    Clear away all the content from this file. We don't want the default configuration.

    Next, copy/paste the following into the file:

        "version": "2.0.0",
        "tasks": [
              "label": "Run code",
              "type": "shell",
              "command": "node ${file}",

    Let's understand what's happening here...

    The "tasks" key contains information about various tasks. Each task is represented by an object with a couple of properties.

    In our case, we've created just one task and given it three properties: "label", "type" and "command".

    1. "label" specifies the label of the task — the name with which it appears when we go on to select and execute a given task.
    2. "type" specifies the type of the command — where to run the command. Usually, this would be set to "shell" which means that the task should be run inside a terminal.
    3. "command" specifies the actual command to execute inside the shell.

    In our case, we've labeled the task as "Run code" — this is the name with which we'll refer to the task later on. The name is chosen because the task is meant to ... well ... run some JavaScript code.

    Besides this, we've set the task's command to "node ${file}" with the special value ${file} in it which denotes the file task variable we briefly discussed above for referring to the path to the file to execute.

    When the Run code task is invoked in VS Code, ${file} in node ${file} is replaced with the absolute path to the current file open in the editor and then the complete command executed in the terminal.

  4. Configure keyboard shortcut

    With the task successfully configured, we are now just left with adding a keyboard shortcut in VS Code to initiate the Run code task.

    Go on and press Ctrl + K followed by Ctrl + S on the keyboard to open the keyboard shortcuts window. From here, go on to the top right corner and select the icon for Open Keyboard Shortcuts (JSON).

    This opens up the JSON file keybindings.json where we can update VS Code's keybindings (i.e. keyboard shortcuts).

    Copy/paste the following into the file:

          "key": "ctrl+numpad1",
          "command": "workbench.action.tasks.runTask",
          "args": "Run code"
          "key": "ctrl+shift+delete",
          "command": "workbench.action.terminal.kill"

    What this code does is simply bind the sequence of keys Ctrl + Numpad1 with executing the task called Run code that we just defined above; and the sequence of keys Ctrl + Shift + Delete with killing the terminal when we're done executing a JavaScript program.

    You can choose any key sequences you find convenient for yourself for each of these actions.

    Read more about keybindings.json at Key Bindings for Visual Studio Code.

    And with this, we have successfully configured Visual Studio Code to run Node.js at the click of just two keys.

    Return to the hello.js file and press the keys Ctrl + Numpad1. This should launch the integrated terminal and ultimately execute the file.

    This is just spectacular!

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage