用法與示例#

用法#

node [options] [V8 options] [script.js | -e "script" | - ] [arguments]

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

示例#

這是一個使用 Node.js 編寫的Web 伺服器示例,它會響應 '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!,則表示伺服器正在工作。