Let’s start using Node.js by creating our first script in this environment and running it from the command console.
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.
Creating the Script
Now simply create a folder anywhere on your computer. Inside it, create a new file called, for example, hola_mundo.js
. The name doesn’t matter, but the extension must be js
(JavaScript).
Now, let’s open this file with any text editor or our favorite IDE, and inside it, we write the following code in hola_mundo.js
:
console.log("Hello World in Node.js!");
In this code, we use the console.log()
function from Node.js to print “Hello World in Node.js!” to the console. It’s not much, but as a first program, it’s not bad!
Running the Program
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 hola_mundo.js
This command tells Node.js to execute the hola_mundo.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 said that the files must have a .js
extension. They can actually 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 modules in JavaScript in a later article.
Management with NPM
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 for us. Its use is so important in development today that you have a whole course dedicated to NPM at this link 👇
Download the code
All the code from this entry is available for download on Github