search
HomeWeb Front-endJS TutorialLearn more about some features in Node.js_node.js

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
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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool