
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
package.json:
mkdir myapp && cd myapp
npm init -y
```:ml-citation{ref="5" data="citationList"}
该文件记录项目元信息和依赖配置,包含`dependencies`(生产依赖)、`devDependencies`(开发依赖)等字段:ml-citation{ref="4,6" data="citationList"}。
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"} npm install <package>@<version>:ml-citation{ref="6" data="citationList"} npm update <package>:ml-citation{ref="6" data="citationList"} npm install -g <package>(如npm install -g nodemon):ml-citation{ref="6,7" data="citationList"} 在package.json的scripts字段定义命令,例如:
"scripts": {
"start": "node index.js",
"test": "jest"
}
通过npm run <script>执行(如npm start或npm test)
npm install -g yarn,使用yarn add <package>安装依赖:ml-citation{ref="6" data="citationList"}。 以上流程覆盖了从环境搭建到项目开发的完整链路,可根据实际需求选择工具链组合
在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