node [options] [V8 options] [script.js | -e "script" | - ] [arguments]
有关更多信息,请参阅命令行选项文档。
使用 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('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 hello-world.js
这样的输出应该出现在终端中:
Server running at http://127.0.0.1:3000/
现在,打开任何首选的网络浏览器并访问 http://127.0.0.1:3000
。
如果浏览器显示字符串 Hello, World!
,则表示服务器正在工作。