Server-Side JavaScript for Backends, API Servers, and Web Apps

在这里插入图片描述

SECTION 1

With the creation of Node.js, developers can now use the same language, namely JavaScript, on both the client and server. Additionally, due to the single-threaded event loop architecture of Node.js, developers can also perform IO-intensive operations (such as responding to Hypertext Transfer Protocol, or HTTP, requests) in a much swifter and simpler manner.

通过创建Node.js,开发人员现在可以在客户端和服务器上使用相同的语言,即JavaScript。此外,由于Node.js的单线程事件循环体系结构,开发人员还可以以更快,更简单的方式执行IO密集型操作(例如, 响应超文本传输协议或HTTP请求)

While Node.js is not the first technology suite to introduce JavaScript on the server side of the equation or the first to use a single-threaded event loop to handle work, it has been the most effective technology thus far to aggregate these concepts. Combined with the ubiquity of the Node Package Manager (NPM), Node.js has cemented its place as the de facto standard for server-side JavaScript.

Resources

  • Node.js Official Website: The official Node.js website containing download links for the latest version of Node.js, as well as the official API documentation for Node.js.
  • Node.js Developer Guides: The official Node.js developer guides, which include detailed and pragmatic examples of how to use Node.js in a practical environment, including samples on creating a Hello World application, debugging existing applications, and understanding the minutia of the Node.js APIs.
  • NodeSchool: An open source project dedicated to teaching developers using Node.js as a programming basis; NodeSchool hosts numerous international events and there are numerous international chapters throughout Asia, Europe, North America, Latin America, Africa, and the South Pacific.
  • Node.js Github: The official Node.js Foundation GitHub, containing the source code for Node.js and its associated projects; also used to manage the open and resolved issues associated with Node.js and its companion projects.
  • Node.js LinkedIn Group: The official Node.js LinkedIn Group (invitation only).
  • NPM Official Website: The official NPM website containing download links for the latest version of NPM and documentation for getting started with NPM, installing existing packages, creating new packages, and using the NPM command line tool; also contains a complete list of the packages uploaded to the NPM repository.

SECTION 2

Architecture

The Node.js architecture can be divided into two main objectives: (1) handling events of interest using the event loop and (2) executing JavaScript on a server rather than in a browser. Prior to understanding these ideas, though, it is essential to understand the differences between synchronous and asynchronous programming.

Synchronous VS Asynchronous Programming

The main difference between synchronous and asynchronous programming is how each deals with a blocking operation, where a task takes a non-trivial amount of time to complete or waits on external input to complete (which may never come and, therefore, the task may never complete). In synchronous programming, the thread that handles the task blocks and waits for the task to complete before doing any more work. In asynchronous programming, the thread delegates the work to another thread (or the operating system) and continues executing the next instruction. When the background thread completes the task, it notifies the original thread, allowing the original thread to handle the now-completed task.

同步编程和异步编程之间的主要区别在于,每个编程如何处理阻塞操作,即任务花费了很短的时间来完成或等待外部输入来完成(这可能永远不会完成,因此任务可能永远不会完成)在同步编程中,线程在处理任务块并等待任务完成后再执行更多工作。在异步编程中,线程将工作委托给另一个线程(或操作系统),并继续执行下一条指令。当后台线程完成任务时,它会通知原始线程,从而允许原始线程处理现在完成的任务。

These differences can be illustrated using an analogy. Suppose a restaurant has a kitchen, a bar, and one waitress. Since the waitress has numerous tables to serve, she cannot take drink orders from a table and wait at the bar until the drinks are done before taking food orders for the table. Likewise, the waitress cannot wait at the kitchen until a submitted food order is completed before serving another table. Instead, the waitress takes drink orders, and if ready, food orders for a table, gives the bartender the drink order, and gives the kitchen the food order. She then proceeds to serve the next table, repeating this process for each table she must serve.

Between providing the bartender with new drink orders, the waitress checks to see if any drink orders have been fulfilled. If there are fulfilled orders, she takes the drinks to the table that ordered them. Likewise, if the kitchen has completed a food order, the waitress takes the food to the table that ordered it. Although there is only one waitress, she is able to simultaneously serve multiple tables because she offloads time-consuming work to the bartender and the kitchen and does not block, waiting for an order to be fulfilled. When either the bartender or the kitchen completes an order, she handles the completed order by bringing it to the table that made the order.

This is asynchronous programming in action. Had the waitress instead taken drink orders and waited at the bar for the order to be completed before returning to the table to take food orders, she would have been operating synchronously. In the case of Node.js, an event loop (akin to the waitress) is used to cyclically check worker threads or the operating system (akin to the bar or the kitchen) to see if offloaded work has been completed. This helps ensure that performing a blocking operation in Node.js does not bring the system to a halt until the operation completes.

对于Node.js,事件循环(类似于女服务员)用于循环检查工作线程或操作系统(类似于酒吧或厨房)以查看卸载工作是否已完成。这有助于确保在操作完成之前,在Node.js中执行阻止操作不会使系统暂停。

The Event Loop

Unlike many large-scale frameworks, Node.js application code executes using a single thread. Instead of creating a series of threads and assigning each a task, Node.js uses an event loop, allowing a developer to register callback functions to execute when an event of interest occurs. For example, instead of creating a new thread to block and handle each HTTP request received by the server, a developer registers a function with the Node.js framework that Node.js uses to handle the request. This allows Node.js to asynchronously execute the callback function whenever it deems most effective.

与许多大型框架不同,Node.js应用程序代码使用单个线程执行。Node.js使用事件循环,而不是创建一系列线程并为每个任务分配任务,而是使事件发生时,开发人员可以注册回调函数以执行。例如,开发人员没有创建新的线程来阻止和处理服务器收到的每个HTTP请求,而是向Node.js框架注册了一个函数,Node.js使用该函数来处理该请求。这允许Node.js在认为最有效的时候异步执行回调函数。

This scheme has many important advantages, including:

  1. The developer is not responsible for handling the nuances of multithreading, such as deadlock avoidance and race conditions.

    开发人员不负责处理多线程的细微差别,例如避免死锁和争用条件

  2. It is possible to make non-blocking IO calls, or if desired, block with a handful of timer-based APIs.

    可以进行非阻塞的IO调用,或者如果需要,可以使用少量基于计时器的API进行阻塞

  3. Callbacks encapsulate the complete logic for handling an event, allowing Node.js to queue the handling logic to be executed when most effective.

    回调封装了用于处理事件的完整逻辑,从而允许Node.js在最有效的时候将要执行的处理逻辑排队

The core of the Node.js event-driven architecture is the event loop, illustrated below.

Node.js事件驱动的体系结构核心是事件循环

在这里插入图片描述

Node.js event loop starts by processing a single JavaScript file, which in turn registers callbacks for its events of interest. For each callback function registered, a reference counter is incremented, allowing Node.js to track how many callbacks are still left to be executed.

Node.js事件循环通过处理单个JavaScript文件开始,该JavaScript文件又为其感兴趣的事件注册回调。对于每个已注册的回调函数,引用计数器都会增加,从而使Node.js可以跟踪处理要执行回调的个数。

As the event loop proceeds, it executes each step, or phase, in the loop (the green and blue circles), handling each of the events associated with each phase. Once the callback reference count reaches 0, the event loop exits and the Node.js process terminates. If the reference count is greater than 0 at the end of a loop iteration, the loop executes again. Commonly, the reference count will not decrement to 0, and thus, Node.js will continue handle events (such as HTTP requests) indefinitely, unless the process is manually terminated.

随着事件循环的进行,它执行循环中的每个步骤或阶段(绿色和蓝色圆圈),进而处理与每个阶段相关联的所有事件。一旦回调引用计数达到0,事件循环就会退出,Node.js进程也会终止。如果在循环迭代结束时引用计数大于0,则循环将再次执行。通常,引用计数不会减少到0,因此,除非手动终止进程,否则Node.js将无限期地继续处理事件(例如HTTP请求)

Event Loop Phases

The green circles in the event loop represent Node.js code that is executed, while the blue circles represent application code that is executed in response to events that occur within the Node.js code. For example, the Timeout phase represents the Node.js code that is executed to find timer events that have expired. Once these events have been collected, the blue application code is executed to handle these timeout events.

事件循环中的绿色圆圈代表执行的Node.js代码,而蓝色圆圈代表响应于Node.js代码中发生的事件而执行的应用程序代码。例如,超时阶段表示执行Node.js代码以查找已过期的计时器事件。一旦收集了这些事件,就会执行蓝色应用程序代码来处理这些超时事件

The four phases of the event loop are:

  1. Timeout: Checks to see if any timeouts have occurred (i.e. registered using the setTimeout or setInterval functions). For example, if a timer is set in application code for 200 ms and at least 200 ms has expired since the initiation of the timer, the timer is declared expired; once the expired timers have been queued, the callback associated with each timer is executed. This process continues until all expired timers have been handled.

    超时: 检查是否发生任何超时(即使用setTimeout或setInterval函数注册).例如,如果在应用程序代码中设置了200毫秒的计时器,并且自计时器启动以来至少已过期200毫秒,则该计时器被声明为已过期;一旦将到期的计时器排入队列,便会执行与每个计时器关联的回调。此过程将继续进行,直到处理完所有过期的计时器为止

  2. Unicorn: IO events, such as completed file system and network events, are handled. This process continues until all IO events for which callbacks have been registered have been handled.

    处理诸如已完成的文件系统和网络事件之类的IO事件。继续此过程,直到处理了已为其注册了回调的所有IO事件

  3. setImmediate : Events declared via the setImmediate function in the previous loop iteration are executed. This process continues until all setImmediate callback functions have been executed.

执行在上一个循环迭代中通过setImmediate函数声明的事件。此过程将继续执行,直到所有setImmediate回调函数均已执行为止

  1. Close: Internal clean-up is executed (i.e. closing sockets) and any callbacks associated with these events are executed. This process continues until all associated callbacks have been executed.

    执行内部清理(即关闭套接字),并执行与这些事件关联的所有回调。该过程将继续,直到所有关联的回调都已执行

Once all of the callbacks associated with the Close phase have been executed, the callback reference count is checked. If the count is greater than 0, the loop is repeated; if the reference count equals 0, the loop is exited and the Node.js process is terminated.

一旦执行了与关闭阶段关联的所有回调,便会检查回调引用计数。如果计数大于0,则重复循环。如果引用计数等于0,则退出循环并终止Node.js进程。

Resolved Promises and nextTicks

Within each of the application code steps (blues circles), all callbacks — called promises in this context — are executed and all callback functions registered using the nextTick function are executed. Once all registered promises and nextTick callbacks have been completed, the user code circle is exited and the next phase of the event loop is entered.

在每个应用程序代码步骤(蓝色圆圈)中,将执行所有回调,并执行所有使用nextTick功能注册的回调函数。一旦完成所有已注册的Promise和NextTick回调,将退出用户代码并进入事件循环的下一阶段。

Note that promises and nextTick callbacks are executed in a sub-loop, as promises and nextTick callbacks can introduce more callbacks to be executed in order to handle the current promise or nextTick callback. For example, recursively calling nextTick within a nextTick callback will queue up a callback that must be completed before execution of the event loop can continue. Note that developers should be wary of making recursive nextTick calls, as this may starve the event loop, not allowing the next callback to be completed or next phase of the loop to be entered. See the documentation on understanding nextTick for more information.

请注意,promise和nextTick回调在子循环中执行,因为promise和nextTick回调可以引入更多要执行的回调以处理当前的promise或nextTick回调。例如,在nextTick回调中递归调用nextTick将使必须在事件循环执行继续之前完成的回调排队。请注意,开发人员应警惕进行递归nextTick调用,因为这可能会使事件循环饿死,不允许完成下一个回调或进入循环的下一阶段。请参阅有关了解nextTick的文档以获取更多信息

nextTick vs. setImmediate

One of the unfortunate blunders in Node.js is the naming of the nextTick and setImmediate functions (see the morning keynote at Node.js Interactive Europe 2016 for more information). The former is used to execute the supplied callback at the completion of the current callback, while the latter is used to defer the execution of the supplied callback until the next iteration of the event loop.

前者用于在当前回调完成时执行提供的回调,而后者用于推迟执行所提供的回调直到事件循环的下一次迭代

Developers should, therefore, be careful not to confuse the use of these two functions and accidently apply them in the reverse manner.

因此,开发人员应注意不要混淆这两个功能的使用,并以相反的方式意外的使用它们

async and await

Although promises allow for deferred, non-blocking execution, they also have a major disadvantage: They are syntactically scrupulous when chained. For example, creating a chain of promises in Node.js (or JavaScript in general) results in code that resembles the following:

尽管Promise允许延迟执行,不阻塞的执行,但它们也有一个主要缺点:在链接时,它们在语法上是谨慎的。例如,在Node.js(或通常的JavaScript)中创建一个promise链,其结果类似于以下代码:

someObject.call()
    .then(response1 => {
        anotherObject.call(response1)
            .then(response2 => {
                thirdObject.call(response2)
                    .then(response3 => {
                        // Do something with 3rd response
                    })
                    .catch(console.error);
            })
            .catch(console.error);
    })
    .catch(console.error);

Asynchronous chains such as these (disparagingly referred to as the pyramid of doom) can be lead to unreadable code and difficult to debug applications. With the advent of version 5.5 of the V8 JavaScript engine (see below) in October 2016, Node.js applications can now utilize the async and await keywords introduced in JavaScript ES2017. This allows the above code to be reduced to the following:

诸如此类的异步链(被贬义为“毁灭金字塔”)可能会导致代码无法读取并且难以调试应用程序。随着2016年10月V8 JavaScript引擎5.5版本的出现(见下文),Node.js应用程序现在可以利用JavaScript ES2017中引入的async和await关键字。这样可以将上面的代码简化为以下代码:

const runCalls() = async() => {
    try {
        const response1 = await someObject.call();
        const response2 = await anotherObject.call(response1);
        const response3 = await thirdObject.call(response2);
    catch (err) {
        console.error(err); 
    }
};
runCalls();

The use of the async keyword creates an asynchronous function that removes much of the boilerplate code and repetition required for the resolution of promises. Within asynchronous functions, the await operator can be used to wait for a promise to be resolved and return its resolved value. In the snippet above, response1 is not assigned until the promise associated with someObject.call() resolves, after which the response1 is assigned the value of the resolved someObject.call() promise. Likewise, anotherObject.call(response1) is not executed until response1 has been assigned after the resolution of someObject.call() . If any of the awaited functions throws an error (which was previously caught using the .catch(...) syntax), the catch clause of the try-catch block will handle the error (since the await operator throws any errors received when resolving the promise it is awaiting on).

使用async关键字会创建一个异步函数,该函数将删除promise解析所需的许多样板代码和重复代码。在异步函数中,可以使用await运算符来等待promise被解析并返回其解析值。在上面的代码段中,直到与someObject.call()相关联的promise解析后才分配response1,此后为response1分配已解析的someObject.call() promise的值。同样,在someObject.call()解析后分配了response1之前,不会执行anotherObject.call(response1)。如果任何等待的函数抛出错误(以前使用.catch(…)语法捕获),则try-catch块的catch子句将处理该错误(因为await运算符抛出解析时收到的任何错误等待的承诺)

It is important to note that the above code, although seemingly asynchronous, is actually asynchronous. The await operator simply abstracts an underlying promise (e.g. one returned from someObject.call()) and allows code to be written to handle asynchronous code in a seemingly synchronous manner.

等待操作符只是抽象了一个底层promise(例如,从someObject.call()返回的promise), 并允许编写代码以看似同步的方式处理异步代码

Server-Side JavaScript

The second key to the success of Node.js is that developers write Node.js server applications in JavaScript. This allows developers to write server-side applications in the same language in which they are accustomed to writing client-side applications. Apart reducing the learning curve, this allows developers to reuse portions of client code in server applications and vice-versa.

Node.js成功的第二个关键是开发人员使用JavaScript编写Node.js服务器应用程序。这使开发人员可以使用习惯于编写客户端应用程序的相同语言来编写服务器端应用程序。除了减少学习曲线外,这还使开发人员可以在服务器应用程序中重用部分客户端代码,反之亦然

The V8 JavaScript Engine

The ability of Node.js to execute JavaScript on the server is achieved by deploying the Chrome V8 JavaScript engine in a standalone environment rather than within the confines of a browser. While JavaScript engines are often relegated to browsers in order to interpret and execute JavaScript code retrieved from a server, Node.js incorporates the V8 JavaScript engine to execute JavaScript in any environment that supports Node.js, as illustrated in the figure below.

通过在独立环境中而不是在浏览器范围内部署Chrome V8 JavaScript引擎,可以实现Node.js在服务器上执行JavaScript的能力。虽然JavaScript引擎通常被委派给浏览器以解释和执行从服务器检索到的JavaScript代码,但是Node.js结合了V8 JavaScript引擎,可以在任何支持Node.js的环境中执行JavaScript,如下图所示

在这里插入图片描述

Since the V8 JavaScript engine is written in C++, Node.js includes a binding layer that allows application code to be written in JavaScript but execute natively through the JavaScript engine. Above the binding layer, Node.js includes an API layer — written in JavaScript — providing core functionality, such as managing sockets and interfacing with the file system through Node.js (see the list of Node.js APIs below for more information). At the top of the stack, developers create applications using the Node.js API layer in conjunction with third-party libraries and APIs.

由于V8 JavaScript引擎是用C ++编写的,因此Node.js包含一个绑定层,该绑定层允许用JavaScript编写应用程序代码,但可以通过JavaScript引擎本地执行。在绑定层之上,Node.js包括一个用JavaScript编写的API层,提供了核心功能,例如管理套接字以及通过Node.js与文件系统接口。在堆栈的顶部,开发人员使用Node.js API层以及第三方库和API来创建应用程序

Along with the V8 JavaScript engine, Node.js also includes the Unicorn Velociraptor Library (libuv), which houses the Node.js event loop and the internal mechanisms used to process registered callback functions. Node.js also includes a set of supporting libraries that allow Node.js to perform common operations, such as opening a socket, interfacing with the file system, or starting an HTTP server. While libuv and the Node.js supporting libraries are written in C++, their functionality can be accessed by Node.js applications using the API and bindings layer, as illustrated below.

除V8 JavaScript引擎外,Node.js还包括Unicorn Velociraptor库(libuv),该库包含Node.js事件循环和用于处理已注册回调函数的内部机制。Node.js还包括一组支持库,这些库允许Node.js执行常见的操作,例如打开套接字,与文件系统接口或启动HTTP服务器。虽然libuv和Node.js支持库是用C ++编写的,但是Node.js应用程序可以使用API和绑定层来访问它们的功能,

在这里插入图片描述

Isomorphic JavaScript

The ability of Node.js to render JavaScript on the server has created a natural extension in web development: Isomorphic JavaScript. Sometimes termed universal JavaScript, isomorphic JavaScript is JavaScript that can run on both the client and the server. In the early days of webpages, static Hypertext Markup Language (HTML) pages were generated by the server and rendered by the browser, providing a simplified User Experience (UX). While these webpages were slow to render, since a single click required the loading of an entirely new page, Search Engine Optimization (SEO) was straightforward, requiring that SEO crawlers parse a static HTML page and follow anchored links to obtain a mapping of a website.

Node.js在服务器上呈现JavaScript的能力在Web开发中创建了自然的扩展:同构JavaScript。同构JavaScript有时称为通用JavaScript,同构JavaScript是可以在客户端和服务器上运行的JavaScript。在网页的早期,服务器生成静态的超文本标记语言(HTML)页面,然后由浏览器呈现这些页面,从而提供了简化的用户体验(UX)。尽管这些网页的呈现速度很慢,但是由于单击一次需要加载一个全新的页面,因此搜索引擎优化(SEO)十分简单,要求SEO搜寻器解析静态HTML页面并遵循锚定链接来获取网站映射

As JavaScript was introduced to the client and rendered by the browser, Single-Page Applications (SPAs) became the de-facto standard. Compared to static webpages, SPAs allow users to quickly and seamlessly transition from one page to another, requiring that only JavaScript Object Notation (JSON) or eXtensible Markup Language (XML) data be transferred from the server to the client, rather than an entire HTML page. While SPAs do have many speed and UX advantages, they commonly require an upfront load time (which is usually accompanied by a loading message) and are difficult to tune for SEO, since crawlers can no longer obtain a static view of a page without rendering a large portion of the SPA themselves.

随着JavaScript引入客户端并由浏览器呈现,单页应用程序(SPA)成为事实上的标准。与静态网页相比,SPA允许用户从一个页面快速无缝地过渡到另一页面,仅要求将JavaScript对象表示法(JSON)或可扩展标记语言(XML)数据从服务器传输到客户端,而不是整个HTML页。尽管SPA确实具有许多速度和UX优势,但它们通常需要预先加载时间(通常会附带加载消息),并且难以针对SEO进行调整,因为抓取工具无法在不呈现页面的情况下获取页面的静态视图。SPA本身的很大一部分

Isomorphic JavaScript is a happy-medium between these two extremes. Instead of performing all of the page generation on the server or all on the client, applications can be run on both the client and the server, providing for numerous performance optimizations and SEO tunings. Companies such as Twitter have even gone so far as to reduce initial load times to 1/5 of those experienced with client-only rendering by offloading the generation of webpages to the server, removing the need for the client to load the entire SPA before rendering the first page displayed to users. Apart from performance and SEO improvements, isomorphic JavaScript allows developers to share code between the client and server, reducing the logical duplication experienced when implementing many large-scale web applications (such as domain and business logic being written in one language on the server and repeated in another language in the SPA). For more information, see Isomorphic JavaScript: The Future of Web Apps by Spike Brehm (of Airbnb).

同构JavaScript是介于这两种极端之间的快乐媒介。可以在客户端和服务器上运行应用程序,而不必在服务器上或客户端上执行所有页面生成操作,从而提供了许多性能优化和SEO调整。Twitter之类的公司甚至通过将网页的生成工作从服务器上卸载,从而消除了客户端在渲染前加载整个SPA的需要,这将初始加载时间减少到只有客户端渲染的初始加载时间的1/5。向用户显示的第一页。除了性能和SEO改进之外,同构JavaScript还允许开发人员在客户端和服务器之间共享代码,从而减少了在实现许多大型Web应用程序(例如以一种语言在服务器上编写并重复的域和业务逻辑)时遇到的逻辑重复SPA中的另一种语言)

SECTION 3

Quick Start

The first step to using Node.js is downloading the Node.js installer, which can be found on the official Node.js website (the source code for Node.js can also be obtained this Downloads page). Note that the installer provides both the Node.js command line tool and the Node Package Manager (NPM) tool.

Once the installer is ready, the installation can be verified by checking the version of Node.js using the following command:

node -v

To run a JavaScript file using Node.js, simply execute the following command, where file.js is the name of the JavaScript file to be executed:

node file.js

For example, a file named index.js can be created with the following content:

console.log(“Hello, world!”);

…and executed using the following command:

node index.js

Executing this file results in the following output:

Hello, world!

const http = require('http');

http.createServer((request, reponse) => {
    const { method, url } = request;
    
    reponse.writeHead(200, {'Content-Type': 'application/json'});
    reponse.write(`{'message': 'Received a ${method} request with context path '${url}'}`);
}).listen(8080);

console.log('Started Server');

The pertinent naming of the functions in the Node.js APIs makes the above code nearly readable in English, where a server is created (listening on port 8080) that handles incoming requests by setting the status of the response header to 200 (OK) and the content type of the response to application/json. The handler then writes a JSON message containing the request method and URL to the response body and closes the response body with the end method.

中创建了一个服务器(在端口8080上侦听),该服务器通过将响应标头的状态设置为200(确定)来处理传入的请求,然后对application / json的响应的内容类型。然后,处理程序将包含请求方法和URL的JSON消息写入响应主体,并使用end方法关闭响应主体

SECTION 4

Common APIs

Node.js ships with a vast array of powerful APIs that can significantly reduce application development time. A complete list of APIs included with Node.js can be found in the Node.js API documentation.

API NameDescription
BufferAn optimized abstraction API that allows developers to interact with octet streams. Since the release of ECMAScript 2015 (ES6), this API has changed significantly (primarily with respect to the instantiation of Buffer objects); developers should consult the official documentation closely to ensure that best practices (such as instantiation through factory methods) are followed. Note that the Buffer API is a global API and therefore does not necessitate the require function to import this API.
Child ProcessA collection of synchronous and asynchronous functions for spawning new processes and executing native commands (i.e. ls) and command line scripts (i.e. .bat and .sh).
CryptoA cryptographic library that includes wrapper functions for OpenSSL hashes, keyed-Hash Message Authentication Codes (HMACs), ciphers, digital signatures, and the Diffie-Hellman Key Exchange (DHKE). Note that it is possible to build Node.js without cryptographic support and, therefore, an error can be thrown when importing the cryptographic API through require(‘crypto’).
DebuggerAn inspection framework that allows developers to debug Node.js application code and interface with the V8 Engine inspector APIs.
EventsAn asynchronous library designed for emitting and handling named events. This library includes abstractions for executing handlers in an asynchronous or synchronous (executing listeners in the order in which they were registered) and handling repeated events.
HTTPA simple yet powerful API for handling incoming HTTP requests. This API includes straightforward methods to establish an HTTP handler and configure desired responses while also allowing developers to adjust more fine-grained options, such as timeouts and permissible numbers of concurrent sockets that can be open to handle requests.
ModulesAn API that allows developers to interact with Node.js modules (such as imported Node.js files), similar to classpath management in Java or package management in Python. This API allows developers to control common aspects of a module, such as exports, as well as more complicated aspects of modules, such as caching. The module API is a global API and does not require an explicit import of the form require(‘module’).
NetA network API that provides for the creation clients and servers for Transmission Control Protocol (TCP) connections, as well as Inter-process Communication (IPC) sockets in both Windows and Unix-based systems. In the specific case of HTTP servers, the HTTP module should be favored; when more general TCP sockets are needed, developers should use the Net module.
ProcessAn API that allows developers to interface with the current Node.js execution process context. This API includes functionality for managing lifecycle events (i.e. exiting the current Node.js process), extracting information about the current execution environment (i.e. supplied command line arguments), and interaction with related processed (i.e. sending IPC messages to parent processes).
StreamAn abstraction API for stream data. This API is used throughout the core APIs of Node.js (i.e. HTTP requests and standard output — stdou — are both streams) and is very useful for understanding the fundamental implementation of other Node.js APIs.

SECTION 5

Third-Party Modules and Frameworks

The growth of Node.js has facilitated the creation of numerous supporting NPM packages and frameworks built on top of the Node.js environment, including the following:

Package NameDescription
sailsA Model-View-Controller (MVC) framework, akin to Ruby on Rails for Node.js, for production or enterprise-level applications. See the Sails.js documentation for more information.
expressA minimalist web application framework that supports the creation HTTP-based APIs. See the Express.js website for more information.
colorsStylizer for console text, including the foreground color, background color, weight (i.e. bold), transforms (i.e. underline or strikethrough), etc.
momentDate abstractions including functionality for comparing, parsing, displaying, and manipulating dates. Also includes support for date locales.
asyncSimple but rich functions for handling asynchronous flow control and functional programming in JavaScript. See the Async documentation for more information.
rxjsSupport for observable behavior and functional programming. See the ReactiveX JavaScript documentation for more information.
browserifyBundler for Node.js modules and its associated dependencies for ease of access through browsers. See the Browserify website for more information.

A list of the most depended upon packages can be found at the official NPM repository. For more Node.js frameworks, see the Node Frameworks website.

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
}

This script can then be executed using the following command:

npm start

This in turn executes the script, which prints Hello, world! in red to the console.

SECTION 6

Governance and Contribution

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
}

This script can then be executed using the following command:

npm start

This in turn executes the script, which prints Hello, world! in red to the console.

SECTION 6

Governance and Contribution

The Node.js Foundation is primarily responsible for the governance of the Node.js project.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值