Home  >  Article  >  Web Front-end  >  4 JS Essentials Node.js Developers Must Know_node.js

4 JS Essentials Node.js Developers Must Know_node.js

WBOY
WBOYOriginal
2016-05-16 15:14:27894browse

This article summarizes 4 Node.js key points for developers.

1. Non-blocking or asynchronous I/O

Since Node.js is a server-side framework, one of its main jobs is to handle browser requests. In a traditional I/O system, each request is issued after the previous request arrives. So this is called blocking I/O. The server will block other requests to process the current request, causing the browser to wait.

Node.js does not handle I/O this way. If a request takes a long time to process, Node.js will send the request to an event loop and continue processing the next request in the call stack. When the deferred request is processed, it notifies Node.js and the browser responds.

The following uses an example to illustrate.

Blocking I/O

// take order for table 1 and wait...
var order1 = orderBlocking(['Coke', 'Iced Tea']);
// once order is ready, take order back to table.
serveOrder(order1);
// once order is delivered, move on to another table.
// take order for table 2 and wait...
var order2 = orderBlocking(['Coke', 'Water']);
// once order is ready, take order back to table.
serveOrder(order2);
// once order is delivered, move on to another table.
// take order for table 3 and wait...
var order3 = orderBlocking(['Iced Tea', 'Water']);
// once order is ready, take order back to table.
serveOrder(order3);
// once order is delivered, move on to another table.

In this restaurant example, the waiter receives the menu instructions, waits for the meal to be processed, and then brings the meal to the table after the meal is processed. While the waiter was waiting for his meal to be processed, he would refuse other customers' menu orders.

Non-blocking I/O

// take order for table 1 and move on...
orderNonBlocking(['Coke', 'Iced Tea'], function(drinks){
 return serveOrder(drinks);
});
// take order for table 2 and move on...
orderNonBlocking(['Beer', 'Whiskey'], function(drinks){
 return serveOrder(drinks);
});
// take order for table 3 and move on...
orderNonBlocking(['Hamburger', 'Pizza'], function(food){
 return serveOrder(food);
});

In non-blocking mode, the waiter will inform the chef of the menu instructions he has received, and then receive the instructions for the next table. When the first table of meals is finished, he will serve the dishes for that table and then continue to receive instructions from other guests. In this way, the waiter will not waste time by blocking instructions.

2. Prototype

Prototype is a complex concept in JS. In typical inheritance mechanism languages ​​such as Java or C++, in order to achieve code reuse, you must first create a class and then generate objects through it or generate objects through class extension. But there is no similar concept of classes in JS. After creating an object in JS, you need to extend the object or create a new object through it. This is called prototypal inheritance.

Each JS object is connected to a prototype object and inherits the properties of that object. Each object is associated with a predefined JS Object.prototype. If you search for object properties through obj.propName or obj['propName'> but the search fails, you can try to search through obj.hasOwnProperty('propName'). The JS runtime will search in the prototype Find properties in an object. If the property does not exist in the prototype chain, an undefined value will be returned.

Let us illustrate with the following example:

if (typeof Object.create !== 'function') {
  Object.create = function (o) {
    var F = function () {};
    F.prototype = o;
    return new F();
  };
var otherPerson = Object.create(person);

When you create a new object, you must select a prototype-based object. Here, we have added a create method to the object function. The create method creates an object based on another object and passes it in as a parameter.

When we change a new object, its prototype remains unchanged. However, when we change a prototype object, the change affects all objects based on that prototype.

3. Modules

If you have ever used packages in Java, Node.js components are similar. If not, don’t worry; components are actually simple JS files used to implement specific functions. The purpose of the component pattern is to make your work easier. To use components, you have to import JS files just like you import packages in JAVA. There are two types of components in Node.js

Core Modules - Core modules are pre-compiled in conjunction with the Node.js library. Its purpose is to open up functions frequently used by programmers and avoid duplication of work. Common core components include HTTP, URL, EVENTS, FILE SYSTEM, etc.

User-defined modules (UserDefined Modules) - User-defined modules are components provided to users to implement specific functions. When the core components are not enough to meet the needs of programmers, custom components can come in handy.

Components are extracted through the require function. If this is a core component, the parameter is the component name. If this is a user-defined component, the parameter is its component path in the file system. For example:

// extract a core module like this
var http = require('http);
// extract a user defined module like this
var something = require('./folder1/folder2/folder3/something.js');

4. 回调(Callbacks)

在JS中,函数是第一类对象。也就是说你可以像对常规对象那样对函数进行所有操作。例如指派函数到一个变量,把这些作为参数传给方法,把它们声明为对象的属性,甚至是把它们从函数里返回。

回调在JS中是异步函数,可以作为参数传递给其它函数或从其它函数里执行或返回而后再执行。这是回调的基本概念。

当我们把一个回调函数作为参数传递给另外的函数时,我们传递的仅仅是函数的定义;换言之,我们不会知道回调函数的执行时间。这完全依赖于回调函数机制。它会在稍后某个时间点进行回调调用。这是Node.js的非阻塞或异步行为的基本概念,可用下例进行说明:

setTimeout(function() {
  console.log("world");
}, 2000)
console.log("hello");

这是一个最简单的调用。我们把一个匿名函数作为参数进行传递,作用是为setTimeout函数进行控制台的输出记录登记。因为这仅仅是个函数定义,我们不知道函数何时会被执行。这取决于setTimeout函数的second参数,即2S后。

首先,second记录语句记录了对控制台的输出,2S后,在回调函数中的记录语句记录了输出的内容。

// output
hello
world

写在最后

以上4点对Node.js开发者来说是要彻底理解和掌握的,建议多动手来好好体会这4个要点的含义。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn