Node.js 简介

¥Introduction to Node.js

Node.js 是一个开源和跨平台的 JavaScript 运行时环境。它是几乎所有类型项目的流行工具!

¥Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!

Node.js 在浏览器之外运行 V8 JavaScript 引擎,即 Google Chrome 的核心。这使 Node.js 的性能非常出色。

¥Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.

Node.js 应用在单个进程中运行,不会为每个请求创建新线程。Node.js 在其标准库中提供了一组异步 I/O 原语,可防止 JavaScript 代码阻塞,并且通常,Node.js 中的库是使用非阻塞范例编写的,这使得阻塞行为成为例外而不是常态。

¥A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

当 Node.js 执行 I/O 操作(如从网络读取、访问数据库或文件系统)时,Node.js 不会阻塞线程并浪费 CPU 周期等待,而是会在响应返回时恢复操作。

¥When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.

这使 Node.js 能够使用单个服务器处理数千个并发连接,而​​不会带来管理线程并发的负担,这可能是错误的重要来源。

¥This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Node.js 具有独特的优势,因为数百万为浏览器编写 JavaScript 的前端开发者现在能够编写服务器端代码以及客户端代码,而无需学习完全不同的语言。

¥Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.

在 Node.js 中,可以毫无问题地使用新的 ECMAScript 标准,因为你不必等待所有用户更新其浏览器 - 你可以通过更改 Node.js 版本来决定使用哪个 ECMAScript 版本,并且还可以通过使用标志运行 Node.js 来启用特定的实验性功能。

¥In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.

Node.js 应用示例

¥An Example Node.js Application

Node.js 最常见的示例 Hello World 是一个 Web 服务器:

¥The most common example Hello World of Node.js is a web server:

const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

要运行此代码段,请将其保存为 server.js 文件并在终端中运行 node server.js

¥To run this snippet, save it as a server.js file and run node server.js in your terminal.

此代码首先包含 Node.js http 模块

¥This code first includes the Node.js http module.

Node.js 有一个很棒的 标准库,包括对网络的一流支持。

¥Node.js has a fantastic standard library, including first-class support for networking.

httpcreateServer() 方法创建一个新的 HTTP 服务器并返回它。

¥The createServer() method of http creates a new HTTP server and returns it.

服务器设置为监听指定的端口和主机名。当服务器准备就绪时,将调用回调函数,在这种情况下通知我们服务器正在运行。

¥The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running.

每当收到新请求时,就会调用 request 事件,提供两个对象:请求(http.IncomingMessage 对象)和响应(http.ServerResponse 对象)。

¥Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object).

这两个对象对于处理 HTTP 调用至关重要。

¥Those 2 objects are essential to handle the HTTP call.

第一个提供请求详细信息。在此简单示例中,未使用此功能,但你可以访问请求标头和请求数据。

¥The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.

第二个用于将数据返回给调用者。

¥The second is used to return data to the caller.

在这种情况下:

¥In this case with:

res.statusCode = 200;

我们将 statusCode 属性设置为 200,以指示成功响应。

¥we set the statusCode property to 200, to indicate a successful response.

我们设置了 Content-Type 标头:

¥We set the Content-Type header:

res.setHeader('Content-Type', 'text/plain');

我们关闭响应,将内容作为参数添加到 end()

¥and we close the response, adding the content as an argument to end():

res.end('Hello World\n');

更多示例

¥More Examples

有关超出 hello world 的 Node.js 示例列表,请参阅 https://github.com/nodejs/examples

¥See https://github.com/nodejs/examples for a list of Node.js examples that go beyond hello world.

阅读时间
7 min read
目录
  1. Node.js 应用示例
  2. 更多示例