# Node.js使用入门
Node.js的使用主要涉及安装、项目初始化、依赖管理以及脚本执行等核心环节，具体方法如下：

## 安装Node.js
在Ubuntu系统上可通过以下步骤安装：

更新软件包列表：sudo apt update
安装Node.js稳定版：sudo apt install nodejs
验证安装：node -v查看版本号
安装npm（通常随Node.js自动安装）：npm -v验证

若需特定版本，可通过PPA安装，如Node.js 18.x

curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

## 项目初始化
1. 创建项目目录并初始化`package.json`：  
```bash
mkdir myapp && cd myapp
npm init -y
```:ml-citation{ref="5" data="citationList"}  
该文件记录项目元信息和依赖配置，包含`dependencies`（生产依赖）、`devDependencies`（开发依赖）等字段:ml-citation{ref="4,6" data="citationList"}。

## 依赖管理
- &zwnj;**安装依赖**&zwnj;：  
  - 生产依赖：`npm install <package>`（如`npm install express`）:ml-citation{ref="6" data="citationList"}  
  - 开发依赖：`npm install <package> --save-dev`（如`npm install jest --save-dev`）:ml-citation{ref="4,6" data="citationList"}  
- &zwnj;**版本控制**&zwnj;：  
  - 指定版本：`npm install <package>@<version>`:ml-citation{ref="6" data="citationList"}  
  - 更新依赖：`npm update <package>`:ml-citation{ref="6" data="citationList"}  
- &zwnj;**全局安装**&zwnj;：`npm install -g <package>`（如`npm install -g nodemon`）:ml-citation{ref="6,7" data="citationList"}  

## 脚本执行
在`package.json`的`scripts`字段定义命令，例如：  
```json
"scripts": {
  "start": "node index.js",
  "test": "jest"
}
```
通过`npm run <script>`执行（如`npm start`或`npm test`）

## 其他工具
- &zwnj;**Yarn**&zwnj;：替代npm的包管理工具，安装更快：`npm install -g yarn`，使用`yarn add <package>`安装依赖:ml-citation{ref="6" data="citationList"}。  
- &zwnj;**nvm**&zwnj;：管理多Node.js版本，适合开发环境切换。  

以上流程覆盖了从环境搭建到项目开发的完整链路，可根据实际需求选择工具链组合

## Node.js升级到最新
在Ubuntu系统上升级Node.js到最新版本，可以通过多种方式实现。以下是最常见的方法：

方法1：使用nvm（Node Version Manager）
‌步骤1‌：安装nvm（如果尚未安装）

打开终端，运行以下命令来安装nvm：

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

或者使用wget：
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

‌步骤2‌：安装Node.js

安装nvm后，重新打开一个终端或者运行以下命令来激活nvm：

source ~/.bashrc

然后，使用nvm安装Node.js的最新版本：

nvm install node