The basic concept of Nodejs

Source: Internet
Author: User
Tags emit event listener tojson

1.node installation and related configuration.

2.NODE.JSREPL (Interactive interpreter)

Similar to the console, you can enter a command and accept a response from the system.

Features of the REPL:

1. READ: Read user input, parse input JS data structure, and store in memory.

2. Execution: Executes the input data structure.

3. Print: Output results.

4. Cycle: Can cycle 1, 2, 3 operation instructions CTRL + C two times exit.

Open node Terminal: Node opens.

Operator: + 、-、 *,/, also supports changing the precedence of parentheses.

Variable definition: Use var to define variables. Common output API:console.log ().

Multiline expressions: This refers to loops, which are consistent with the loops in JS. Each output line returns, and node automatically detects whether it is a continuous multiline expression.

Underline _ Variable: You can use the underscore variable to get the result of the operation of the previous expression.

REPL command:

CTRL + C exits the current terminal.

CTRL + C two consecutive times, exit node REPL

Ctrl+d Exit Node REPL

Up/down arrow-View input history commands.

tab lists the current command

. Help lists Use commands

. Break exits multi-line expression

. Clear exit Multiline expression

The. Save filename Saves the current Node REPL session to the specified file.

. load filename Loads the file contents of the current Node REPL session.

3. Node. JS callback function

The immediate manifestation of node. JS asynchronous programming is callbacks.

Asynchronous programming relies on callbacks to implement, but it cannot be said that the use of callbacks is asynchronous.

The callback function is called after the task is completed, and node uses a large number of callback functions, all of which are supported by the node's API.

Note: Blocking is performed sequentially, and not blocking is not required in order, so if you need to handle the parameters of the callback function, we need to write it inside the callback function.

4.node.js Event Loop

node. JS is a single-process single-threaded application, but supports concurrency through events and callbacks, so performance is high.

Each of the APIs in node. JS is asynchronous (the idea here is that each API supports callbacks.) Refer to the third section) and run as a standalone thread, using an asynchronous function call, and handling concurrency.

node. js basically all of the event mechanisms are implemented using the observer pattern in the design pattern.

The node. JS single thread resembles an event loop that enters a while (true) until there is no event and the observer exits, and each asynchronous event generates an event watcher. The callback function is called if an event occurs.

With multiple events built into node. js, you can introduce the events module and bind and listen to events by instantiating the Eventemitter class.

In node: The function that performs the asynchronous operation takes the callback function as the last parameter, and the callback function accepts the error object as the first argument.

5.node.js Eventemitter

All asynchronous I/O operations of node. JS send an event to the event queue when it is finished.

Many objects in node. JS Distribute Events: A Net.server object distributes an event every time a new connection is made, and an Fs.readstream object emits an event when the file is opened. All events that are generated are objects. An instance of Eventemitter.

Eventemitter class

The events module provides only one object, events. Eventemitter. The core of Eventemitter is the encapsulation of event triggering and event listener functionality.

// Introducing the Events module var events = require (' Events '); // Create a Eventemitter object var new events. Eventemitter ();

An error event is triggered when an Eventemitter object is instantiated again. When a new listener is added, the Newlistener event is triggered and when the listener is removed, the RemoveListener event is triggered.

A brief example illustrates Eventemitter usage:

// event.js File var Eventemitter = require (' Events '). Eventemitter; var New Eventemitter (); Event.on (function() {    console.log (' some_event event Trigger ');    }); SetTimeOut (function() {    event.emit (' some_event '1000);

Each event of the Eventemitter consists of an event name and several parameters, the event name is a string, which usually conveys a certain meaning, and for each event Eventemitter supports several event listeners.

When an event is triggered, the listener registered to the event is called sequentially, and the event arguments are passed as a callback function parameter.

Simple example code:

// event.js File var events = require (' Events '); var New events. Eventemitter (); Emitter.on (' someevent ',function(arg1, arg2) {    console.log (' listener1 ') , ARG1,ARG2);}); Emitter.on (' someevent ',function(arg1, arg2) {   console.log (' Listener2 ', arg1 , arg2); }) Emitter.emit (' someevent ', ' arg1 parameter ', ' arg2 parameter ');

Execution Result:

In the example above, emitter registered two listeners for the event and then triggered the event. This is the simplest use of eventemitter.

Eventemitter provides multiple properties, such as on for event binding, and emit to trigger an event.

The specific API

Error Event

Eventemitter defines a special event error that contains the semantics of the error, and we usually trigger an error event when we encounter an exception.

When error is triggered, eventemitter specifies that if a listener is not responding, node. JS will take it as an exception, exit the program and output an error message.

We typically set up listeners for the object that will trigger the error event, to prevent the entire program from crashing after a mistake occurs.

About Eventemitter,

Most of the time we only inherit it from the object, including FS, net, and HTTP. As long as the core module that supports incident response is a subclass of Eventemitter. There are two reasons:

1. Objects with an entity function implement events that conform to semantics, and the listener and occurrence of events should be a method of an object.

The object mechanism of 2.js is based on prototype, supporting partial inheritance, inheriting Eventemitter does not disrupt the original inheritance relationship of the object.

Note: add: An unbound event in the practice queue triggers an error event and the program throws an unexpected end if the error event is not bound.

6.node.js Buffer (buffers)

JS has only a string data type and no binary data type. However, when processing a stream, binary data must be used, so the buffer class is defined in node. js, which is used to create a buffer that stores the binary data specifically.

Buffer and character encoding

The buffer instance is typically used to represent sequences of encoded characters, such as UTF-8, UCS2, Base64, or hexadecimal encoded data, which can be converted between a buffer instance and a normal JavaScript string by using explicit character encoding.

Const BUF = buffer.from (' Runoob ', ' ASCII '); // output 72756e6f6f62console.log (buf.tostring (' hex ')); // output cnvub29iconsole.log (buf.tostring (' base64 '));

The character encodings currently supported by node. JS include:

ASCII supports only 7-bit ASCII data. This encoding is very fast if the setting is removed from the high.

UTF8 multibyte-encoded Unicode characters, and many web pages and other document formats use UTF-8.

Utf16le 2 or 4 bytes, a small byte encoded Unicode character. Support for proxy pairs (u+100000 to U+10FFF).

USC2 the alias of the Utf16le.

Base64 BASE64 encoding.

Latin1 a way to encode buffer into a byte-encoded string.

The alias of binary Latin1.

Hex encodes two bytes into two hexadecimal bytes.

Create a buffer class

Buffer provides the following API to create the buffer class:

//create a buffer with a length of 10 and a 0 fillConst BUF1 = Buffer.alloc (10);//creates a buffer with a length of 10 and is populated with 0x1. Const BUF2 = Buffer.alloc (10,1);//creates a buffer with a length of 10 and is not initialized. //This method is faster than calling Buffer.alloc (). //However, the returned buffer instance may contain old data. //Therefore, you need to use fill () or write () overrides. Const BUF3 = Buffer.allocunsafe (10);//create a buffer containing [0x1, 0x2, 0x3]Const BUF4 = Buffer.from ([]);//Create a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74]. Const BUF5 = buffer.from (' Tést ');//Create a Buffer that contains Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. Const BUF6 = buffer.from (' tést ', ' latin1 ');
Write buffers

Grammar:

The syntax for writing to the node buffer is as follows:

Buf.write (string[, offset[, length]][,encoding])

Parameters:

Writes the offset position in string to BUF based on the character encoding of the encoding. The length parameter is the number of bytes written. If BUF does not have enough space to hold the entire string, it is written only as part of the string, and only partially decoded characters are not written.

return value:

Returns the actual write size. If the buffer space is insufficient, only a partial string is written.

Reading data from a buffer

The syntax for reading the node buffer data is as follows:

Buf.tostring ([encoding[, Start[,end]])

BUF = Buffer.alloc (+);  for (var i = 0; i <; i++) {    = i + +;} Console.log (buf.tostring (' ASCII '));        // output: abcdefghijklmnopqrstuvwxyzconsole.log (buf.tostring (' ASCII ', 0, 5));    // output: ABCDEconsole.log (buf.tostring (' UTF8 ', 0, 5));    // Output: ABCDE // use ' UTF8 ' encoding, and output: ABCDE

Convert buffer to JSON object

Syntax: convert node buffer to the function syntax format of a JSON object:

Buf.tojson ()

When the string is converted to a buffer instance, json.stringify () implicitly invokes the Tojson ();

Const BUF = Buffer.from ([0x1, 0x2, 0x3, 0x4, 0x5= json.stringify (buf); // output: {"type": "Buffer", "Data": [1,2,3,4,5]}  = Json.parse (JSON, (key, value) = =  {return value && value.type = = = ' Buffer '? c8>    Buffer.from (value.data):    value;}); // output: <buffer 05>console.log (copy);

Buffer Merge

Grammar:

Buffer.concat (list[, Totallength])

var buffer1 = Buffer.from (' rookie tutorial '); var buffer2 = Buffer.from ((' www.runoob.com ')); var buffer3 = Buffer.concat ([Buffer1,buffer2]); Console.log ("Buffer3 content:" + buffer3.tostring ());

Buffer comparison

Grammar:

Buf.compare (Otherbuffer);

 var  buffer1 = Buffer.from (' ABC '  var  result = Buffer1.compare (buffer2);  if  (Result < 0 + "before" + Buffer2 + " else  if  (Result = = 0 + "and" + Buffer2 + "" else   {Console.log (buffer1  + "after" + Buffer2 + "
        /span>                  

The basic concept of Nodejs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.