Node.js: How to write your first Node.js program

Let’s jump right in and create our first Node.js program.

If you don’t have a local projects folder yet, create a dev folder in your home directory or on your desktop.

We’ll keep all the projects organized there.

In that folder, create a first-node-app directory, and open it in VS Code.

Inside it, create a file named index.js

This will be the main file of our program.

It actually does not matter how you name it. It could be called app.js or whatever, like dog.js. But index.js is common for the entry point of your program.

Type console.log('test') in the index.js file, and save it.

Now open the terminal inside VS Code, using the menu Terminal → New Terminal

Now type node index.js.

The program will execute and its output will be displayed in the terminal:

💁‍♂️ Note that the Node.js program we ran exited and returned control to the terminal (you can see there’s a new terminal prompt) because it executed all the lines we had, completed its job, and it quit. Some Node programs you write could be long-running, like servers that stay active until you terminate their execution manually.

Now that JavaScript is running outside of the browser, it can do many more things, because we’re running it outside of the browser sandbox, a security tool that prevents your computer to be hacked all the time just by visiting random websites.

JavaScript in the browser is limited, for good reasons.

But outside of it, as we’ll see, it can access the network, the filesystem, the database, configuration options, and a lot more.

Lessons in this unit:

0: Introduction
1: Installing Node.js on your computer
2: ▶︎ How to write your first Node.js program
3: Importing other files
4: Using npm to install packages
5: Using built-in modules
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!