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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment