在Ubuntu上使用Node.js進行開發,可以按照以下步驟進行:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm install --lts
node -v
npm -v
sudo apt update
sudo apt install nodejs npm
node -v
npm -v
curl -sL https://deb.nodesource.com/setup_current.x | sudo -E bash -
sudo apt install nodejs
node -v
npm -v
npm install
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
例如,創建一個簡單的Node.js服務器:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World
');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
保存為server.js
,然后在終端中運行:
node server.js
打開瀏覽器,訪問http://localhost:3000
,你應該會看到“Hello World”的消息。
以上步驟可以幫助你在Ubuntu上成功設置Node.js開發環境,并開始進行開發。