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


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:

BASH
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:

BASH
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

BASH
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

BASH
$ 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:

BASH
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:

BASH
npm --version

If the output looks like 10.9.0, it means npm is available.

▶ Example: Complete Verification Process

BASH
$ node --version
v22.11.0

$ npm --version
10.9.0

$ node -e "console.log('Node.js is working!')"
Node.js is working!

Tip: node -e allows 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:

BASH
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:

JAVASCRIPT
> function add(a, b) {
...   return a + b;
... }
undefined
> add(3, 5)
8

▶ Example: Quickly testing code in the REPL

JAVASCRIPT
> 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
▶ Try it Yourself

4. Run Your First Script

(1) Create a JavaScript file

Create a new file named hello.js:

JAVASCRIPT
const greeting = 'Hello, Node.js!';
console.log(greeting);

const version = process.version;
console.log(`Running on ${version}`);

▶ Example: (2) Run using the node command

BASH
node hello.js

▶ Example: Running a script and passing parameters

Created by greet.js:

JAVASCRIPT
const name = process.argv[2] || 'World';
console.log(`Hello, ${name}!`);
console.log(`Node version: ${process.version}`);
console.log(`Current directory: ${process.cwd()}`);
▶ Try it Yourself

Execute:

BASH
$ 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

BASH
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

BASH
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

BASH
$ mkdir my-app && cd my-app
$ npm init -y
JSON
{
  "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.

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:

JSON
{
  "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

100%
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:

BASH
# 1. Install and switch to Node.js 22 LTS
nvm install 22
nvm use 22

# 2. Verify the Installation
node --version
npm --version
TEXT 📖 Display only
v22.11.0
10.9.0
BASH
# 3. Create a project directory and initialize it
mkdir bob-project
cd bob-project
npm init -y

Created by index.js:

JAVASCRIPT
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:

BASH
node index.js
TEXT 📖 Display only
Project: bob-project
Node.js: v22.11.0
Directory: /home/bob/bob-project
Step 1: setup
Step 2: config
Step 3: deploy

❓ FAQ

Q What is the difference between nvm and installing Node.js directly?
A When you install Node.js directly, you can only use one version, and the old version is overwritten when you upgrade; nvm allows you to install multiple versions at the same time and switch between them at any time, so you can use different versions for each project without them interfering with one another.
Q What is the difference between npm init -y and npm init?
A 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.
Q How do I enter multi-line code in the REPL?
A The REPL automatically detects unclosed parentheses or curly braces and switches to multi-line mode (displaying the ... prompt). You can also type .editor to enter multi-line editor mode.
Q How do I choose a Node.js version?
A Prioritize LTS (Long-Term Support) versions, which provide at least 30 months of maintenance support and are suitable for production environments. Current versions include the latest features but have a shorter maintenance cycle, making them suitable for trying out new features.
Q What is the difference between ^ and ~ in package.json?
A ^ allows upgrading to the latest version within the same major version (e.g., ^1.2.3 allows 1.x.x but not 2.x.x), while ~ only allows upgrading to the latest version within the same minor version (e.g., ~1.2.3 allows 1.2.x but not 1.3.x).
Q Are the nvm-windows commands the same as the nvm commands on macOS and Linux?
A The core commands (install, use, ls) are essentially the same, but nvm-windows is a standalone implementation, so some advanced features may differ. We recommend referring to the respective documentation.
Q What should I do if I can't find the npm command after installing Node.js?
A npm is installed along with Node.js. If you can't find it, your environment variables may not be configured correctly. Try reinstalling Node.js or manually adding the Node.js installation directory to your system PATH.

📖 Summary


📝 Exercises

  1. Install Node.js 22 LTS using nvm and set it as the default version
  2. Enter the REPL, define a function that calculates the sum of all even numbers in an array, and verify the result
  3. Create a project directory, initialize it using npm init -y, and then modify the name and description fields in package.json
  4. Write a script info.js that outputs the current Node.js version, the operating system platform (process.platform), and the runtime (process.uptime()).
  5. Install the Node.js Extension Pack in VS Code, configure launch.json, and successfully debug and run a script
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏