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

May 16, 2016 pm 04:35 PM
node.js characteristic

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Introduction to the differences between win7 home version and win7 ultimate version Introduction to the differences between win7 home version and win7 ultimate version Jul 12, 2023 pm 08:41 PM

Everyone knows that there are many versions of win7 system, such as win7 ultimate version, win7 professional version, win7 home version, etc. Many users are entangled between the home version and the ultimate version, and don’t know which version to choose, so today I will Let me tell you about the differences between Win7 Family Meal and Win7 Ultimate. Let’s take a look. 1. Experience Different Home Basic Edition makes your daily operations faster and simpler, and allows you to access your most frequently used programs and documents faster and more conveniently. Home Premium gives you the best entertainment experience, making it easy to enjoy and share your favorite TV shows, photos, videos, and music. The Ultimate Edition integrates all the functions of each edition and has all the entertainment functions and professional features of Windows 7 Home Premium.

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

Master the key concepts of Spring MVC: Understand these important features Master the key concepts of Spring MVC: Understand these important features Dec 29, 2023 am 09:14 AM

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

An article to talk about how to efficiently develop presentation layer Node.js applications An article to talk about how to efficiently develop presentation layer Node.js applications Apr 17, 2023 pm 07:02 PM

How to use Node.js for front-end application development? The following article will introduce you to the method of developing front-end applications in Node, which involves the development of presentation layer applications. The solution I shared today is for simple scenarios, aiming to allow front-end developers to complete some simple server-side development tasks without having to master too much background knowledge and professional knowledge about Node.js, even if they have no coding experience.

Choose the applicable Go version, based on needs and features Choose the applicable Go version, based on needs and features Jan 20, 2024 am 09:28 AM

With the rapid development of the Internet, programming languages ​​are constantly evolving and updating. Among them, Go language, as an open source programming language, has attracted much attention in recent years. The Go language is designed to be simple, efficient, safe, and easy to develop and deploy. It has the characteristics of high concurrency, fast compilation and memory safety, making it widely used in fields such as web development, cloud computing and big data. However, there are currently different versions of the Go language available. When choosing a suitable Go language version, we need to consider both requirements and features. head

See all articles