在Ubuntu上使用Node.js搭建服務器的步驟如下:
首先,你需要在Ubuntu系統上安裝Node.js。你可以使用NodeSource提供的安裝腳本來安裝特定版本的Node.js。
打開終端(Terminal)。
運行以下命令來添加NodeSource倉庫:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
這里的16.x
是你想要安裝的Node.js版本,你可以根據需要更改。
安裝Node.js:
sudo apt-get install -y nodejs
驗證安裝:
node -v
npm -v
這兩個命令分別會顯示Node.js和npm的版本號。
在你的工作目錄下創建一個新的項目目錄:
mkdir my-node-server
cd my-node-server
在項目目錄中初始化一個新的Node.js項目:
npm init -y
這會創建一個package.json
文件,其中包含項目的元數據。
在項目目錄中創建一個名為server.js
的文件:
touch server.js
使用你喜歡的文本編輯器(如VSCode、Sublime Text等)打開server.js
文件,并添加以下代碼:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
在終端中運行以下命令來啟動服務器:
node server.js
你應該會看到輸出:Server running at http://127.0.0.1:3000/
。
打開瀏覽器,訪問http://127.0.0.1:3000/
,你應該會看到頁面上顯示“Hello World”。
如果你想要更快速地搭建一個功能更豐富的服務器,可以使用Express框架。首先,安裝Express:
npm install express
然后,修改server.js
文件:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
再次啟動服務器并測試:
node server.js
訪問http://localhost:3000/
,你應該會看到頁面上顯示“Hello World!”。
通過以上步驟,你就可以在Ubuntu上使用Node.js搭建一個簡單的服務器了。