Setting Up Node.js
In this section, we'll walk through setting up Node.js on your system. We'll use Node Version Manager (NVM) to install and manage Node.js versions, which provides flexibility for working with different Node.js versions across projects.
Installing Node Version Manager (NVM)
Node Version Manager (NVM) is a tool for installing and managing multiple versions of Node.js on your system. This is particularly useful when working on different projects or trying out new features as Node.js evolves.
To install NVM:
Open your terminal.
For macOS and Linux, run the following curl command:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
For Windows, you can use NVM for Windows. Download and install it from: https://github.com/coreybutler/nvm-windows/releases
After installation, close and reopen your terminal.
Verify NVM installation by typing:
nvm --version
This should display the installed NVM version.
Installing Node.js using NVM
With NVM installed, you can easily install Node.js:
- To install the latest version of Node.js, run:
nvm install node
- If you need a specific version, you can specify it. For example:
nvm install 21.7.3
- To set a default Node.js version, use:
nvm alias default 21.7.3
Replace 21.7.3
with your preferred version.
Using the LTS Version
LTS stands for Long Term Support. These versions receive active support and critical bug fixes for an extended period, making them ideal for production environments.
I recommend using this throughout the rest of the series to ensure everything we do works as expected.
To install the latest LTS version of Node.js using NVM:
nvm install --lts
And then to use it we use:
nvm use --lts
To set the LTS version as your default, use:
nvm alias default lts/*
Verifying the installation
After installation, verify that Node.js and npm (Node Package Manager, which comes with Node.js) are correctly installed:
Check the Node.js version:
node --version
Check the npm version:
npm --version
Both commands should display their respective version numbers. Don't worry about "npm" for the moment if it's new for you. We will talk about it in a later chapter. We just wanted to confirm everything is working as expected.
Creating your first Node.js script
Now that Node.js is installed let's create a simple script:
Create a new file named
hello.js
in your preferred directory.Open
hello.js
in a text editor and add the following code:
console.log('Hello, Node.js!');
- Save the file.
Running Node.js programs
To run your Node.js script:
Open your terminal.
Navigate to the directory containing your
hello.js
file.Run the script using Node.js:
node hello.js
You should see "Hello, Node.js!" printed in your terminal.
You've just run your first Node.js program. 🎉
Time to update your CV, right?
Next Steps
Now that you have Node.js set up and running, you can start exploring more complex Node.js concepts and applications.
In the next section, we'll dive deeper into Node.js fundamentals.