用法和範例#

用法#

node [選項] [V8 選項] [script.js | -e "script" | - ] [參數]

請參閱 命令列選項 文件以取得更多資訊。

範例#

使用 Node.js 編寫的 網路伺服器 範例,回應為 'Hello, World!'

本文件中的指令以 $> 開頭,以複製它們在使用者終端機中出現的方式。請勿包含 $> 字元。它們用於顯示每個指令的開頭。

未以 $> 字元開頭的行顯示前一個指令的輸出。

首先,請務必下載並安裝 Node.js。請參閱 透過套件管理員安裝 Node.js 以取得進一步的安裝資訊。

現在,建立一個名為 projects 的空專案資料夾,然後導覽至其中。

Linux 和 Mac

mkdir ~/projects
cd ~/projects 

Windows CMD

mkdir %USERPROFILE%\projects
cd %USERPROFILE%\projects 

Windows PowerShell

mkdir $env:USERPROFILE\projects
cd $env:USERPROFILE\projects 

接下來,在 projects 資料夾中建立一個新的原始檔,並將其命名為 hello-world.js

在任何偏好的文字編輯器中開啟 hello-world.js 並貼上以下內容

const http = require('node: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}/`);
}); 

儲存檔案。然後,在終端機視窗中,輸入以下指令執行 hello-world.js 檔案

node hello-world.js 

終端機中應會出現類似以下的輸出

Server running at http://127.0.0.1:3000/ 

現在,開啟任何偏好的網路瀏覽器並前往 http://127.0.0.1:3000

如果瀏覽器顯示字串 Hello, World!,表示伺服器運作正常。