Node.js v22.3.0 文档


¥Usage and example



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

有关详细信息,请参阅 命令行选项 文档。

¥Please see the Command-line options document for more information.



用 Node.js 编写的 web 服务器 的示例,它响应 'Hello, World!'

¥An example of a web server written with Node.js which responds with 'Hello, World!':

本文档中的命令以 $> 开头,以复制其在用户终端中的显示方式。不要包含 $> 字符。它们在那里显示每个命令的开始。

¥Commands in this document start with $ or > to replicate how they would appear in a user's terminal. Do not include the $ and > characters. They are there to show the start of each command.

不以 $> 字符开头的行显示上一个命令的输出。

¥Lines that don't start with $ or > character show the output of the previous command.

首先,确保已经下载并安装了 Node.js。有关更多安装信息,请参阅 通过包管理器安装 Node.js

¥First, make sure to have downloaded and installed Node.js. See Installing Node.js via package manager for further install information.

现在,创建一个名为 projects 的空项目文件夹,然后导航到其中。

¥Now, create an empty project folder called projects, then navigate into it.

Linux 和 Mac:

¥Linux and 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

¥Next, create a new source file in the projects folder and call it hello-world.js.

在任何首选的文本编辑器中打开 hello-world.js 并粘贴以下内容:

¥Open hello-world.js in any preferred text editor and paste in the following content:

const http = require('node:http');

const hostname = '';
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 文件,输入:

¥Save the file. Then, in the terminal window, to run the hello-world.js file, enter:

node hello-world.js 


¥Output like this should appear in the terminal:

Server running at 


¥Now, open any preferred web browser and visit

如果浏览器显示字符串 Hello, World!,则表示服务器正在工作。

¥If the browser displays the string Hello, World!, that indicates the server is working.