Node.js: Installation and Setup
Last updated: 2026-08-26
Bob is a front-end developer who just started working at a tech company. On his first day, his mentor gave him the project repository URL. After cloning it, he ran npm install but got a bunch of errors—it turned out the company’s project was using Node.js 22 LTS, while he was still running the older version 18 on his local machine. Bob was caught in a dilemma because he was worried that upgrading directly might affect other legacy projects. Fortunately, his mentor recommended nvm, which allowed him to switch freely between different Node.js versions, ensuring each project used its own compatible version without interfering with the others. From then on, Bob never had to worry about version conflicts again.
What You'll Learn
- Installing and Switching Between Node.js Versions Using nvm
- Verify that Node.js and npm have been installed successfully
- Execute JavaScript code in the REPL interactive environment
- Write and run your first Node.js script
- Use
npm initto create apackage.jsonproject configuration file
1. Installing and Using nvm
(1) Why do we need nvm?
Node.js is updated frequently, and different projects may depend on different versions. nvm (Node Version Manager) allows you to install multiple versions of Node.js on the same machine and switch between them as needed, thereby avoiding version conflicts.
(2) Install nvm
macOS / Linux:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
Once the installation is complete, restart the terminal or run the following command:
source ~/.bashrc
Windows:
Windows users can use nvm-windows. After downloading the installer, follow the wizard to complete the installation.
▶ Example: (3) Installing and Switching Between Node.js Versions
nvm install 22
nvm use 22
nvm alias default 22
| Command | Description |
|---|---|
nvm install <version> |
Install a specific version |
nvm use <version> |
Switch to a specific version |
nvm ls |
List installed versions |
nvm ls-remote |
List available remote versions |
nvm alias default <version> |
Set as Default Version |
nvm current |
Show the currently used version |
▶ Example: Installing Node.js 22 LTS and Switching
$ nvm install 22
Downloading and installing node v22.11.0...
Now using node v22.11.0 (npm v10.9.0)
$ nvm use 22
Now using node v22.11.0 (npm v10.9.0)
$ nvm current
v22.11.0
(4) Comparison of Node.js Installation Methods
| Method | Advantages | Disadvantages | Suitable Scenarios |
|---|---|---|---|
| Official installation package | Simple and intuitive, one-click installation | Difficult to switch versions, troublesome to uninstall | Beginners who only use one version |
| nvm | Supports multiple versions simultaneously, with flexible switching | Requires separate installation of nvm | Developers working on multiple projects and using multiple versions |
| Package Manager (apt/brew) | Well-integrated with the system | Versions may be outdated; switching is inconvenient | Linux server environment |
2. Verifying the Node.js Installation
(1) Check the Node.js version
Once the installation is complete, open the terminal and enter:
node --version
If the output looks like v22.11.0, it means Node.js has been installed correctly.
(2) Check the npm version
npm is installed along with Node.js. To verify this:
npm --version
If the output looks like 10.9.0, it means npm is available.
▶ Example: Complete Verification Process
$ node --version
v22.11.0
$ npm --version
10.9.0
$ node -e "console.log('Node.js is working!')"
Node.js is working!
Tip:
node -eallows you to execute a single line of JavaScript code directly, which is useful for quick testing.
3. REPL Interactive Environment
(1) Entering and Exiting the REPL
Type node in the terminal to enter the REPL (Read-Eval-Print Loop) interactive environment:
node
To exit: Enter .exit or press Ctrl + C twice.
(2) Common REPL Commands
| Command | Description |
|---|---|
.help |
Show Help |
.exit Exit REPL |
|
.save <file> |
Save the current session to a file |
.load <file> |
Load File into Session |
.clear |
Clear Current Context |
.editor |
Enter Editor Mode (Multi-line Editing) |
(3) Multi-line Input
REPL automatically detects unclosed parentheses and curly braces and enters multi-line input mode:
> function add(a, b) {
... return a + b;
... }
undefined
> add(3, 5)
8
▶ Example: Quickly testing code in the REPL
> const prices = [9.99, 24.5, 3.75, 18.0]
undefined
> prices.filter(p => p > 10).reduce((sum, p) => sum + p, 0)
42.5
> const total = prices.reduce((sum, p) => sum + p, 0)
undefined
> total
56.24
4. Run Your First Script
(1) Create a JavaScript file
Create a new file named hello.js:
const greeting = 'Hello, Node.js!';
console.log(greeting);
const version = process.version;
console.log(`Running on ${version}`);
▶ Example: (2) Run using the node command
node hello.js
▶ Example: Running a script and passing parameters
Created by greet.js:
const name = process.argv[2] || 'World';
console.log(`Hello, ${name}!`);
console.log(`Node version: ${process.version}`);
console.log(`Current directory: ${process.cwd()}`);
Execute:
$ node greet.js Bob
Hello, Bob!
Node version: v22.11.0
Current directory: /home/bob/projects/demo
(3) Introduction to the process Object
process is a global object in Node.js that can be used without require. Common properties:
| Property | Description |
|---|---|
process.version |
Node.js Version |
process.argv |
Command-line argument array |
process.cwd() |
Current working directory |
process.env |
Environment Variable Object |
process.exit() |
Exit Process |
5. Creating package.json
▶ Example: (1) Create interactively using npm init
npm init
npm will prompt you for information such as the project name, version, and description one by one, and will ultimately generate package.json.
▶ Example: (2) Use npm init -y to quickly create a project
npm init -y
-y Skips all questions and generates package.json using default values, making it ideal for a quick start.
▶ Example: package.json generated by npm init -y
$ mkdir my-app && cd my-app
$ npm init -y
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
(3) Description of Key Fields in package.json
| Field | Description | Example |
|---|---|---|
name |
Project Name, required, lowercase with no spaces | "my-app" |
version |
Semantic version number, required | "1.0.0" |
description |
Project Description | "A sample project" |
main |
Input File | "index.js" |
scripts |
Custom Script Commands | {"start": "node index.js"} |
dependencies |
Production Dependencies | {"express": "^4.21.0"} |
devDependencies |
Development Dependencies | {"jest": "^29.7.0"} |
license |
Open Source License | "MIT" |
(4) Semantic version range notation
| Symbol | Meaning | Example | Allowed Versions |
|---|---|---|---|
| None | Exact match | "1.2.3" |
1.2.3 only |
^ |
Compatible with major versions | "^1.2.3" |
≥1.2.3, <2.0.0 |
~ |
Compatible with minor versions | "~1.2.3" |
≥1.2.3, <1.3.0 |
>= |
Greater than or equal to | ">=1.2.3" |
1.2.3 and above |
6. Common Development Tools
(1) Installing and Configuring VS Code
VS Code is the most popular editor for Node.js development, with a built-in terminal and debugger.
(2) Recommended Node.js Extensions
| Extension Name | Function |
|---|---|
| Node.js Extension Pack | Collection of Node.js Development Extensions |
| ESLint | Code Style Checks |
| Prettier | Code Formatting |
| Code Runner | Quickly Run Code Snippets |
| npm IntelliSense | Auto-complete npm module names |
(3) VS Code's Built-in Terminal
Use the keyboard shortcut Ctrl + to open the built-in terminal, so you don't have to switch between the editor and the terminal.
▶ Example: Configuring VS Code to Debug Node.js
Create .vscode/launch.json in the project root directory:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/index.js"
}
]
}
Press F5 to start debugging.
7. The Process of Managing Multiple Versions of Node.js with nvm
flowchart TD
A[Installation nvm] --> B[nvm install 22]
B --> C[nvm install 18]
C --> D[nvm use 22]
D --> E{Project Switching?}
E -->|Enter the Project A| F[nvm use 22]
E -->|Enter the Project B| G[nvm use 18]
F --> H[node --version Verification]
G --> H
H --> I[Run Project]
I --> E
8. Comprehensive Example: Creating a Node.js Project from Scratch
The following walkthrough demonstrates the entire process, from installing Node.js to running your first script:
# 1. Install and switch to Node.js 22 LTS
nvm install 22
nvm use 22
# 2. Verify the Installation
node --version
npm --version
v22.11.0
10.9.0
# 3. Create a project directory and initialize it
mkdir bob-project
cd bob-project
npm init -y
Created by index.js:
const projectName = require('./package.json').name;
const version = process.version;
console.log(`Project: ${projectName}`);
console.log(`Node.js: ${version}`);
console.log(`Directory: ${process.cwd()}`);
const item = ['setup', 'config', 'deploy'];
item.forEach((item, index) => {
console.log(`Step ${index + 1}: ${item}`);
});
Running Projects:
node index.js
Project: bob-project
Node.js: v22.11.0
Directory: /home/bob/bob-project
Step 1: setup
Step 2: config
Step 3: deploy
❓ FAQ
npm init -y and npm init?npm init prompts you for information such as the project name and version one by one; npm init -y skips all prompts and generates a package.json file using default values, making it suitable for quickly creating projects.📖 Summary
- nvm is the preferred tool for managing multiple versions of Node.js; it supports installing, switching between, and setting the default version
node --versionandnpm --versionare used to verify whether the installation was successful- REPL provides an interactive execution environment, ideal for quickly testing code snippets
- Use
node <file>to run a JavaScript script, andprocess.argvto retrieve command-line arguments npm init -yQuickly create apackage.jsonfile—this is the first step in initializing a project- VS Code + Node.js extensions are the most popular combination of development tools
📝 Exercises
- Install Node.js 22 LTS using nvm and set it as the default version
- Enter the REPL, define a function that calculates the sum of all even numbers in an array, and verify the result
- Create a project directory, initialize it using
npm init -y, and then modify thenameanddescriptionfields in package.json - Write a script
info.jsthat outputs the current Node.js version, the operating system platform (process.platform), and the runtime (process.uptime()). - Install the Node.js Extension Pack in VS Code, configure
launch.json, and successfully debug and run a script