Home > Web Front-end > JS Tutorial > Learn more about some features in Node.js_node.js

Learn more about some features in Node.js_node.js

WBOY
Release: 2016-05-16 16:35:29
Original
1220 people have browsed it

Node.js is an emerging backend language designed to help programmers quickly build scalable applications. Node.js has many attractive features, and there are countless reports about it. This article will analyze and discuss features such as EventEmitter, Streams, Coding Style, Linting, and Coding Style to help users have a deeper understanding of Node.js.

As a platform built on the Chrome JavaScript runtime, our knowledge of JavaScript seems to be applicable to node applications; without additional language extensions or modifications, we can apply our front-end programming experience to Backend programming.

EventEmitter (event emitter)

First of all, you should understand the EventEmitter model. It can send an event and allow consumers to subscribe to events of interest. We can think of it as an extension of the callback delivery pattern to an asynchronous function. In particular, EventEmitter will be more advantageous when multiple callbacks are required.

For example, a caller sends a "list files" request to a remote server. You may want to group the returned results and perform a callback for each group. The EventEmitter model allows you to send a "file" callback on each group and perform "end" processing when all operations are completed.

When using EventEmitter, you only need to set the relevant events and parameters.

Copy code The code is as follows:

var EventEmitter = require('events').EventEmitter;
var util = require('util');

function MyClass() {
if (!(this instanceof MyClass)) return new MyClass();

EventEmitter.call(this);

var self = this;
setTimeout(function timeoutCb() {
Self.emit('myEvent', 'hello world', 42);
}, 1000);
}
util.inherits(MyClass, EventEmitter);

The MyClass constructor creates a time trigger with a trigger delay of 1s and a trigger event of myEvent. To use related events, you need to execute the on() method:

Copy code The code is as follows:

var myObj = new MyClass();
var start = Date.now();
myObj.on('myEvent', function myEventCb(str, num) {
console.log('myEvent triggered', str, num, Date.now() - start);
});

It should be noted here that although the subscribed EventEmitter event is an asynchronous event, when the time is triggered, the listener's actions will be synchronized. Therefore, if the above myEvent event has 10 listeners, all listeners will be called in order without waiting for the event loop.

If a subclass of EventEmitter generates an emit('error') event, but no listener subscribes to it, then the EventEmitter base class will throw an exception, causing an uncaughtException to be triggered when the process object is executed. event.

verror

verror is an extension of the base class Error, which allows us to define output messages using printf character format.

Streams

If there is a very large file that needs to be processed, the ideal method should be to read part of it and write part of it. No matter how big the file is, as long as time allows, the processing will always be completed. The concept of stream needs to be used here. Streams are another widely used model in Node, which is the implementation of EventEmitter. Provides readable, writable or full-duplex interfaces. It is an abstract interface that provides regular operation events including: readable, writable, drain, data, end and close. If we can use pipelines to effectively integrate these events, more powerful interactive operations will be achieved.

By using .pipe(), Note can communicate with back-pressure through pipeline. Back-pressure means: only read those that can be written, or only write those that can be read.

For example we are now sending data from stdin to a local file and remote server:

Copy code The code is as follows:

var fs = require('fs');
var net = require('net');

var localFile = fs.createWriteStream('localFile.tmp');

net.connect('255.255.255.255', 12345, function(client) {
Process.stdin.pipe(client);
process.stdin.pipe(localFile);
});

And if we want to send data to a local file and want to use gunzip to compress the stream, we can do this:

Copy code The code is as follows:

var fs = require('fs');
var zlib = require('zlib');

process.stdin.pipe(zlib.createGunzip()).pipe(fs.createWriteStream('localFile.tar'));

If you want to know more about stream, please click here.

Control Flow

Since JS has first-class objects, closures and other functional concepts, callback permissions can be easily defined. This is very convenient when prototyping and can integrate logical permissions as needed. But it also makes it easy to use clumsy built-in functions.

For example, we want to read a series of files in order and then perform a certain task:

Copy code The code is as follows:

fs.readFile('firstFile', 'utf8', function firstCb(err, firstFile) {
doSomething(firstFile);
fs.readFile('secondFile', 'utf8', function secondCb(err, secondFile) {
doSomething(secondFile);
fs.readFile('thirdFile', 'utf8', function thirdCb(err, thirdFile) {
doSomething(thirdFile);
});
});
});

The problem with this model is:

1. The logic of these codes is very scattered and disorderly, and the related operation processes are difficult to understand.
2. No error or exception handling.
3. Closure memory leaks in JS are very common and difficult to diagnose and detect.

If we want to perform a series of asynchronous operations on an input set, using a flow control library is a wiser choice. Vasync is used here.

vasync is a process control library whose idea comes from asynchronous operations. Its special feature is that it allows consumers to view and observe the processing of a certain task. This information is very useful for studying the occurrence process of an error.

Coding Style

Programming style can be said to be the most controversial topic, because it is often casual. Carrots and cabbage, everyone has their own preferences. The important thing is to find a style that works for both the individual and the team. Some traditional inheritance may make the Node development journey better.

1. Name the function
2. Try to name all functions.
3. Avoid closures
4. Do not define other functions within a function. This can reduce many unexpected closure memory leak accidents.
5. More and smaller functions

Although V8 JIT is a powerful engine, smaller and streamlined functions will integrate better with V8. Furthermore, if our functions are small and exquisite (about 100 lines), we will thank ourselves when we read and maintain them.

Check style programmatically: Maintain style consistency and enforce it with an inspection tool. We are using jsstyle.

Linting (code inspection)

The Lint tool can perform static analysis of the code without running it and check for potential errors and risks, such as missing break statements in case switches. Lint is not simply equivalent to style checking, it is more aimed at objective risk analysis rather than subjective style selection. We use javascriptlint, which has rich checking items.

Logging

When we program and code, we need to have a long-term perspective. In particular, consider what tools to use for debugging. An excellent first step is effective logging. We need to identify the information to see what is worth paying special attention to during debugging and what is used for analysis and research during runtime. It is recommended to use Bunyan, a direct Node.jslogging library. The data output format is JSON. To learn more, please click here.

Client Server

If an application has distributed processing capabilities, it will be more attractive in the market. Similar interfaces can be described using the HTTP RESTFul API or raw TCP JSON. This allows developers to combine their Node experience with asynchronous networking environments and the use of streams with distributed and scalable systems.

Commonly used tools:

1. restify

Simply put, this is a tool for building REST services. It provides good viewing and debugging processing support, and supports Bunyan and DTrace.

2. fast

fast is a lightweight tool that uses TCP to process JSON messages. Provides DTrace support, allowing us to quickly identify performance characteristics of the server client.

3. workflow

Workflow is built on restify and can define business processes for a series of remote services and APIs. For example: error status, timeout, reconnection, congestion handling, etc.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template