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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools