在Ubuntu上启动Node.js,首先要安装Node.js和npm,可使用NodeSource仓库安装指定版本,如安装Node.js 18.x:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
安装完成后,创建项目目录,初始化项目并创建服务器文件,如server.js:
mkdir my-node-app
cd my-node-app
npm init -y
在server.js中编写代码,例如创建HTTP服务器:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
最后,在终端中导航到项目目录,使用node命令启动应用:
node server.js
若需后台运行,可使用PM2进程管理器:
sudo npm install -g pm2
pm2 start server.js