nodejs 官網
mkdir /data/tools -p && cd /data/tools
wget https://nodejs.org/download/release/v10.16.0/node-v10.16.0-linux-x64.tar.gz
tar zxvf node-v10.16.0-linux-x64.tar.gz
mv node-v10.16.0-linux-x64 /usr/local/node-v10.16.0
# 修改 PATH
vi /etc/profile
export NODEJS=/usr/local/node-v10.16.0
export PATH=$PATH:$NODEJS/bin
source /etc/profile
npm 設置淘寶源
npm config set registry http://registry.npm.taobao.org/
# 檢查是否更換成功
npm config get registry
安裝 cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
node -v
cnpm -v
升級 npm 版本
npm install npm@6.14.2 -g # 指定版本
npm install npm@latest -g # 最新版本
升級 node 版本
npm install -g n
# 通過 n 來升級 node 版本, n v12.16.2 指定 v12.16.2 版本
/usr/local/node_project/node/bin/n ls
/usr/local/node_project/node/lib/node_modules/n/bin/n v12.16.2
# 備份原來 node 版本,替換成最新的版本
cd /usr/bin/
mv node node_v10.16.0
ln -s /usr/local/bin/node /usr/bin/node
安裝 pm2
cnpm install -g pm2
創建一個應用
mkdir /data/server -p && cd /data/server
vi server.js
var http = require("http");
http.createServer(function(req,res){
res.write('<head><meta charset="utf-8"></head>');
res.write("klvchen nodejs!");
res.end();
}).listen(3000);
## 啟動應用
pm2 start /data/server/server.js --name my-web
訪問
常見命令
npm install pm2 -g # 命令行安裝 pm2
pm2 start app.js --name my-api # 命名進程
pm2 list # 顯示所有進程狀態
pm2 monit # 監視所有進程
pm2 logs # 顯示所有進程日志
pm2 stop all # 停止所有進程
pm2 restart all # 重啟所有進程
pm2 reload all # 0秒停機重載進程 (用於 NETWORKED 進程)
pm2 stop 0 # 停止指定的進程
pm2 restart 0 # 重啟指定的進程
pm2 startup # 產生 init 腳本 保持進程活着
pm2 web # 運行健壯的 computer API endpoint (http://localhost:9615)
pm2 delete 0 # 殺死指定的進程
pm2 delete all # 殺死全部進程
創建一個 npm 項目
mkdir /data/demo && cd /data/demo/
npm init
# 根據以下內容,輸入信息
cat package.json
{
"name": "demo",
"version": "1.0.0",
"description": "klvchen npm demo",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "klvchen",
"license": "ISC"
}
# 新建 index.js
vi index.js
var http = require("http");
http.createServer(function(req,res){
res.write('<head><meta charset="utf-8"></head>');
res.write("klvchen npm demo!");
res.end();
}).listen(3000);
# 啟動
npm run start
# 使用 pm2 進行管理
pm2 start npm --name "npm-demo" -- run start
pm2 list