在 Ubuntu 下运行 Node.js,一般按下面步骤来:
sudo apt update
sudo apt install nodejs npm
检查版本:
node -v
npm -v
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
写一个文件,例如 app.js:
console.log("Hello Node.js");
运行:
node app.js
node
然后直接输入 JS 代码:
> 1 + 2
3
退出按:
Ctrl + D
或
.exit
node app.js arg1 arg2
在 JS 中通过:
console.log(process.argv);
| 命令 | 作用 |
|---|---|
node file.js |
运行 JS 文件 |
npm init |
初始化项目 |
npm install 包名 |
安装依赖 |
npm run 脚本 |
运行 package.json 中的脚本 |
const http = require('http');
http.createServer((req, res) => {
res.end('Hello Ubuntu Node.js');
}).listen(3000);
运行:
node app.js
浏览器访问:
http://localhost:3000
如果你是想 开机自启 / PM2 / Docker / 某个框架(Express、Nest 等),可以告诉我具体需求。