Why we use Node

引言:Node 已经迅速成为一个可行并且真正高效的web 开发平台。在Node 诞生之前,在服务端运行JavasScript 是件不可思议的事情,并且对其他的脚本语言来说,要实现非阻塞I/O 通常需要依赖特殊的类库。但Node 的出现改变了这一切。
本文选自《Node.js硬实战:115个核心技巧》,让我们跟着本文快速的复习一下Node是什么以及他的主要特性有哪些。

Why use Node

  Suppose you are developing an ad server that needs to serve millions of ads every minute. Node's non-blocking I/O will be an efficient solution because the server can maximize all I/O resources without you needing to write special low-level code. Also, if you already have a development team that can write JavaScript, they should be able to directly participate in Node projects. Traditional web platforms won't be able to do this, which is why companies like Microsoft are also aggressively pushing Node, even though they already have platforms as good as .NET. Users of Visual Studio (.NET IDE) can install tools to support IntelliSense for Node, performance monitoring, and even npm. Microsoft has also developed WebMatrix, which not only supports Node directly, but also deploys Node projects. 
  Node uses non-blocking I/O as a way to improve the performance of certain types of applications. JavaScript's traditional event mechanism means it has a relatively convenient and understandable syntax for asynchronous programming. In traditional programming languages, an I/O operation would block the process until it completes. Node's asynchronous file read and write and network APIs mean that the main process can still handle other requests while these relatively slow I/O operations are being handled. The following diagram shows how to use the asynchronous network and file APIs to process multiple tasks at the same time. 
image description
  In the figure, Node's http module receives and parses a new HTTP request①, and then the application code of the server uses the asynchronous interface to pass a callback function into the read function of the database to perform a data query②. While waiting for the data to be returned, the server can read the web page template file ③ from the file system, and this template file is used to display the web page. Once the database has completed the query, the template content and the data returned from the database will be used to render the page ④. 
  While the server is processing this request, the server can also use the available resources to process other requests. By developing this ad serving without having to worry about multithreading, you can use only the most basic JavaScript programming techniques, through Node, to use server I/O resources very efficiently. 
  Other use cases for Node are Web APIs and web crawlers. If you need to download and intercept web page content, Node is the perfect solution because it simulates DOM manipulation and runs client-side JavaScript scripts. And in this scenario, Node has a performance advantage, because the main consumption of the web crawler is the I/O of network and file reading and writing. 
  Node is also a great choice if you need to call or develop a JSON API because it makes manipulating JavaScript objects very easy. Some of Node's web frameworks (such as express) can quickly build JSON APIs. 
  Node is not only limited to web applications, you can create any TCP/IP service you want, such as a network game server, send game status to various players through TCP/IP sockets, and maintain game data in background tasks , which sends data to the player.

When to use Node

  Here are some examples of Node applications to help you think about it like a real Node developer.

Scenario: Advertising Distribution System

  Node's strengths: 
  • Efficiently distributes small pieces of information 
  • Handles potentially slow network connections 
  • Easily scales to multiple processors or servers

Scenario: Game Server

  Node's strengths: 
  • Use JavaScript to build business logic models 
  • Do not use C language to develop server programs that cater to specific networks

Scenario: Content Management System, Blog

  Node's strengths: 
  • Easy to create RESTful JSON APIs for teams already experienced in client-side JavaScript development 
  • Lightweight server, combined with browser-side JavaScript

Main features of Node

  Node 的主要特性是它的标准类库、模块系统以及npm(包管理系统),当然还有很多其他的。 
  实际上Node 最强大的特性是它的标准类库,它主要由二进制类库以及核心模块两部分组成,二进制类库包括libuv ,它为网络以及文件系统提供了快速的事件轮循以及非阻塞的I/O。同时它还有http 类库,所以你可以很快确定你的http 客户端与服务端。 
image description
  上图是对Node 内部的高层次概述,展示了各个模块是如何组合的。 
  Node 的核心模块主要由JavaScript 编写,也就是说,假如你不理解或者你想了解更多细节,你可以直接阅读Node 的源码。这不但包括像网络、文件操作、模块系统,以及stream 这些模块,还包括Node 特有的特性,例如,通过cluster 模块同时运行多个Node进程,以及可以将代码片段封装在事件驱动的异常处理中的domain 模块。 
接下来,我们将从事件开始深入每个核心模块。

1. EventEmitter 事件的接口

  每个Node 开发者迟早会碰到EventEmitter ,一开始,它像是那些只有类库开发者才会使用的东西,但实际上它是大多数Node 核心模块的基础,Stream、网络、文件系统全部继承于它。 
你可以基于EventEmitter 来创建自己基于事件的API,例如你要开发一个paypal 付款处理的模块,你可以让它基于事件,这样Payment 对象的实例可以触发像paid 和refund 这样的事件,通过这样的设计,你可以将这个模块从你的业务逻辑中分离出来,让它可以在其他项目中被重用。 
一个有意思的地方是,stream 模块也是基于EventEmitter 的。

2. Stream:高可扩展性I/O 的基础

  Streams 继承于EventEmitters ,能被用来在不可预测的输入下创建数据,比如网络连接,数据传输速度取决于其他用户正在干什么。通过Node 的stream API,你可以创建一个对象接收关于连接的事件,在接收到新数据时触发data 事件,在结束连接时触发end 事件,在有错误发生时触发error 事件。 
  相比较把许多的回调函数传入一个readable stream 的构造函数,你只订阅你关心的事件要好得多,多个streams 也可以连接起来,这样你可以用一个stream 对象从网络读取数据,把读取到的数据输送到另外一个stream 中加工成另外一个对象,可以把xml 文件的数据读取出来转换成JSON 格式,让JavaScript 操作起来更容易。 
  你可能觉得stream 和事件听上去很抽象,没错,它们的确很抽象,但它们是I/O 模块(例如文件系统和网络)的基础。

3. FS:处理文件

  Node 的文件模块不但可以通过非阻塞的I/O 读写文件,而且它也有同步的方法。你可以通过fs.stat 异步获取文件的信息,也可以通过fs.statSync 同步读取。 
  如果你想通过Stream 的方式高效地处理文件内容,那么你可以通过fs.createReadStream来获得一个ReadableSream 对象。

4. 网络:创建网络客户端与服务端

  网络模块是http 模块的基础,也可以用来创建通用的网络客户端与服务端。尽管Node开发通常指的是web 开发,在第7 章你会看到如何创建TCP 和UDP 的服务,这意味着你并不局限于http 开发。

5. 全局对象与其他模块

  If you have experience developing web applications with Node, perhaps the Express framework, then you probably don't know that you already use core modules like http, net, and fs. Other built-in modules may be less eye-catching, but are also crucial. 
  One example is the design of global objects and methods, such as the process object, which allow you to pass data in and out of standard I/O streams (stdout, stdin). Just like in UNIX or Windows scripts, you can cat the data directly to the Node program. There's also the ubiquitous console object, which all JavaScript developers love, and a global object.

  After understanding Node features, let's take a look at the abridged table of contents of the book "Node.js Hard Action: 115 Core Tips". 
Part 1 Node Basics 
1 Getting Started 
2 Global Variables: The Node Environment 
3 Buffers: Working with Bits, Bytes, and Encodings 
4 Events: Playing with EventEmitter 
5 Streams: The Most Powerful and Most Misunderstood Feature 
6 File Systems: Handling via Asynchronous and Synchronous Methods File 
7 Networking: The True "Hello, World" 
of Node 8 Child Processes: Using Node to Integrate External Applications 
Part 2 Hands-on Tips 
9 Networking: Building Thin Web Apps 
10 Testing: The Key to Writing Robust Code 
11 Debugging: For Identify and fix problems 
12 Node in production: deploying applications securely 
Part 3 Writing modules 
13 Writing modules to master all things Node

  This article is selected from "Node.js Hard Practice: 115 Core Skills", click this link to view it on the official website of the blog post. 
image description

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326455471&siteId=291194637