Installing Node.js the Right Way
Installing Node.js is very straightforward. In this tutorial you'll learn how to install it using nvm, the Node Version Manager.
In the first part of the Node.js Tutorial series, you've learned what Node.js is and why you should learn it. Since you're reading this, I assume you've decided that Node.js is worth learning. It'll be quite a beautiful journey, I assure you!
If you want to get started right away, download and install the Node.js binaries by visiting the official Node.js Downloads page. However, if you want to do it the right way, keep reading to learn about nvm.
Installing nvm
If you want to add more Node.js versions to use for different applications, or to simply keep your Node.js environment organized, I'd recommend installing nvm. Here's how to install it for your specific operating system:
MacOS and Linux
Follow the steps specified in the nvm GitHub repository, or run the following command in your command line Terminal:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
Windows
The windows version requires you to Download and Install the executable from the nvm-windows GitHub repository.
Using nvm
To list the versions of Node.js available to install, run the following command:
nvm ls-remote
This is going to give you a long list of available Node.js versions. I usually choose to install one of the LTS (Long Term Support) versions, which are proven to be stable and have all the latest bug fixes.
For this tutorial, we'll install version 12.14.0 (LTS: Erbium).
nvm install 12.14.0
To check if the chosen node version has been installed properly, run:
node --version
This will return the version number of the currently active Node.js binary. If everything is working, it should say 12.14.0
.
Switching between versions
If you've installed multiple versions using nvm, you can switch between them using the nvm use
command:
nvm use 12.14.0
Getting started ― Hello world!
Now that your Node.js is up and ready to be put to use, we can write and run a small test program, to make sure that you're ready for the next part.
Let's start by creating a file called index.js
. Open up your IDE (Atom, Sublime, VS Code, or WebStorm), create a new file and save it with the name index.js
.
Once you’re done with that, write your first line of Node.js:
// File: index.js
console.log("Hello Node.js!");
Let's run the program! To execute your Node.js file, go back to your command line terminal and navigate to the directory in which you've saved the index.js
file. Once you're there, run:
node index.js
You can see that it will log Hello Node.js!
to the terminal.
What's next?
Well, that was simple! If you've read around about Node.js, you've surely come across require()
statements, used to include code from other files into your application's entry point (the index.js
file).
Next, head over to Understanding Node.js Modules where you'll learn about modules, how they work, and why they're so important.