Language: EN


How to create and run a script with Node.js

Let’s start using Node.js, seeing how to create our first script in this environment, and executing it from the command line.

Don’t worry if it’s your first time with Node.js. One of the reasons for its fame is how well it works and how simple it is. So don’t be afraid.

Before we begin, I assume you already have Node.js installed and working on your system. If not… well, you know, check out the post where we saw how to install it.

Script Creation

Now simply create a folder anywhere on your computer. Inside it, create a new file called, for example, hello_world.js. The name doesn’t matter, but the extension should be js (JavaScript).

Now, open this file with any text editor, or with your favorite IDE, and inside it put this, hello_world.js, write the following code:

console.log("Hello World in Node.js!");

In this code, we use the console.log() function of Node.js to print “Hello World in Node.js!” in the console. It’s not much, but as a first program, it’s not bad!

Program Execution

Once we have written our script in our file, we can call Node.js to execute it using the following command from a terminal console.

node hello_world.js

This command tells Node.js to execute the hello_world.js script. You will see the message “Hello World in Node.js!” printed in the console as a result.

File Extensions: .js vs .mjs

We have said that files must have the extension .js. In reality, they can be .js or .mjs.

  • .js is used for traditional script files
  • .mjs is used to indicate that the file is a JavaScript module

For now, we will focus on .js files, but we will explore JavaScript modules in a later article.

NPM Management

Node.js also comes with NPM (Node Package Manager), which is a package manager for installing and managing Node.js dependencies.

NPM also manages and initializes projects. Its use is so important in development today, that you have an entire course for NPM at this link 👇