项目初始化
¥Project initialization
第一个目标是建立一个简单的 HTML 网页,提供表单和消息列表。为此,我们将使用 Node.JS Web 框架 express
。确保已安装 Node.JS。
¥The first goal is to set up a simple HTML webpage that serves out a form and a list of messages. We’re going to use the Node.JS web framework express
to this end. Make sure Node.JS is installed.
首先让我们创建一个描述我们项目的 package.json
清单文件。我建议你将其放在一个专用的空目录中(我将其称为我的 socket-chat-example
)。
¥First let’s create a package.json
manifest file that describes our project. I recommend you place it in a dedicated empty directory (I’ll call mine socket-chat-example
).
- CommonJS
- ES modules
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"type": "commonjs",
"dependencies": {}
}
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"type": "module",
"dependencies": {}
}
"name" 属性必须是唯一的,不能使用 "socket.io" 或 "express" 这样的值,因为 npm 在安装依赖时会抗诉。
¥The "name" property must be unique, you cannot use a value like "socket.io" or "express", because npm will complain when installing the dependency.
现在,为了轻松地用我们需要的东西填充 dependencies
属性,我们将使用 npm install
:
¥Now, in order to easily populate the dependencies
property with the things we need, we’ll use npm install
:
npm install express@4
安装后,我们可以创建一个 index.js
文件来设置我们的应用。
¥Once it's installed we can create an index.js
file that will set up our application.
- CommonJS
- ES modules
const express = require('express');
const { createServer } = require('node:http');
const app = express();
const server = createServer(app);
app.get('/', (req, res) => {
res.send('<h1>Hello world</h1>');
});
server.listen(3000, () => {
console.log('server running at http://localhost:3000');
});
import express from 'express';
import { createServer } from 'node:http';
const app = express();
const server = createServer(app);
app.get('/', (req, res) => {
res.send('<h1>Hello world</h1>');
});
server.listen(3000, () => {
console.log('server running at http://localhost:3000');
});
这意味着:
¥This means that:
Express 将
app
初始化为可以提供给 HTTP 服务器的函数处理程序(如第 5 行所示)。¥Express initializes
app
to be a function handler that you can supply to an HTTP server (as seen in line 5).我们定义了一个路由处理程序
/
,当我们访问网站首页时,该处理程序会被调用。¥We define a route handler
/
that gets called when we hit our website home.我们让 http 服务器监听端口 3000。
¥We make the http server listen on port 3000.
如果运行 node index.js
,你应该看到以下内容:
¥If you run node index.js
you should see the following:
如果你将浏览器指向 http://localhost:3000
:
¥And if you point your browser to http://localhost:3000
:
到目前为止,一切都很好!
¥So far, so good!
- CommonJS
- ES modules