Nodejs-Basic Library

Source: Internet
Author: User

 

Assert:

This module can be used after require ('assert ') is used for unit testing;

The main function is to determine the expression value. When the expression is false, an exception can be thrown.

 
Assert. fail (actual, expected, message, operator) // The function does not perform operations when actual is equal to the expected value. Otherwise, an exception message is thrown in the format of acturl operator expected, otherwise, the error message is message. Assert (value, message), assert. OK (value, [Message]) assert. equal (actual, expected, [Message]) assert. deepequal (actual, expected, [Message]) // functions of these functions are similar.

Buffer:

This module provides the cache processing capability. The node automatically loads the buffer class, so no require is required;

1) supports encoding (note that the binary method will be canceled in the future, so try not to use it); when converting a buffer into a string, pay attention to Unicode, for example, Buf may lose data at the Unicode boundary. See Concat.

2) buffer Byte Length Buffer. bytelength, which is different from the length of the string class.

VaR STR = 'frequent hands ';
Console. Log (STR + ":" + Str. Length + "characters," + buffer. bytelength (STR, 'utf8') + "bytes ");

Note: the string length is 3, and the byte length is 9;

3) buffer. Concat (list, [totallength]) connects the buffer list into a buffer. This function is very useful in data and end events.

4) BUF. Copy (targebuf...), Buf. Write, Buf [Index], and Buf. Fill read/write Functions

5) read and write numeric functions Buf. writeuint32be/Le, and Buf. readuint32be/Le read and write numeric functions in large-end and small-end mode. These functions are particularly useful in implementation protocols.

Childprocess:

1) communication between sub-processes and processes. The process of each node process is an instance of this class.

2) You can create sub-processes through spawn and exec. Each sub-process has three associated streams, stdout, stdin, and stderr, which can be used to read. in addition, the send function allows communication between parent and child processes.

3) The PID attribute of process indicates the process ID. The kill method can be used to send signals.

4) for message sending, note: the message attributes includeThe node _ prefix is understood as a node reserved message. Therefore, such messages do not generate message Event Notifications. Server objects are shared by sending, then, when the parent and child processes listen to the connect event at the same time on the server, the parent and child will share and process the new connection. After sending and sharing the socket object, the server listener obtains the connected socket, the socket can be passed to the sub-process for processing, and the server will no longer hold the socket (For details, refer to the document ).

Cluster:

Nodejs provides this module to give full play to the performance of multi-core systems.

Working principle: the master creates a worker and uses child process to communicate with each other. When worker calls server. Listen, relevant parameters are sent to the master node. If the master node checks that the handle has a matched handle, the master node returns the handle. Otherwise, the master node creates and returns the handle to the worker. The main purpose is to allow multiple workers to work together, so that the second server won't be able to listen on the same port. (Note: Listen (0) will cause the master to create a socket on the random port. Therefore, if multiple workers want to share the port, they must display the specified port number to call listen ).

Because multiple workers are in accept, the operating system determines which worker is successful.

In addition, adding or reducing worker in the cluster does not affect other worker processes new connections because the worker is independent of each other.

Main cluster events: fork events (triggered when a sub-process is created); online events (sub-processes start to executeCode); Listening event (triggered when the worker process calls listen); disconnect event (when the sub-process fails, the latter calls the disconnect function); exit event (when the sub-process exits ).

Crypto:

This module is used to process encryption, hash, https, and other authentication information.

Debugger:

Google's V8 engine uses the TCP protocol with built-in governor, and node encapsulates some commands in the client. You can use node debug test. js to start debugging.

DNS:

DNS resolution module. In addition to lookup, the resolution functions in this module use C-Ares asynchronous resolution. The lookup function uses the getaddrinfo synchronization method to parse data. C-Ares should be used when a large number of DNS resolution tasks are required.

Events:

The event processing module in node. All released event objects in node are events. eventemitter instances. When an event is triggered, the Associated Function executed is called listeners. In the callback function, this is associated with the events. eventemitter object.

If a class needs to support events, use the following method:

 
VaR eventemitter = require ('events '). eventemitter; var util = require ('util'); function testevent () {eventemitter. apply (this);} util. inherits (testevent, eventemitter); // This statement must be in the definition of testevent. run the command before prototype, because this statement resets the prototype attribute.
 
Testevent. Prototype. test = function () {This. emit ('event1', 'hahahah ');}

Error Event. When an event object exception occurs, the error is usually released. Node has special processing for the error event, that is, if the error event processing function is not set, the node prints the stack by default and exits.

In addition, the enhanced eventproxy module facilitates event usage.

FS:

The module that implements file system operations in nod. Most functions provide synchronous and asynchronous versions. It even provides functions to monitor files or directories.

Global:

Global is not a module. It only introduces some globally available objects or classes.

Note that each module in node is a top-level space. Therefore, variables defined using VAR in one module do not affect the other module. Note: If the VaR definition is not used, the global space will be contaminated.

 
/// Module1.js defines ZCS = 'zhongchangshou'; // module2.js defines var module1 = require ('. /module1.js'); console. log (ZCS); // print the zhongchangshou

In addition, the process, buffer, require function, _ filename, and _ dirname are all immediately available.

The setTimeout and setinterval functions can also be used. Note that the first parameter of the two functions is CB rather than a statement.

HTTP:

1. HTTP. createserver ([requestistener]) will create an HTTP. server class (this class inherits from the eentemitter class). The requestlistener parameter is automatically added to HTTP. server class to the request event processing list.

2. the HTTP. server class inherits from eentemitter and defines the following events:

2.1 request event. This event is triggered every time a client requests it. (A persistent connection may generate multiple requests and trigger multiple events.) The event prototype is as follows:Function (request, response ){},The request is an HTTP. incomingmessage class instance, and the reqponse is an HTTP. serverresponse class instance..

2.2 connection event, indicating that a connection is triggered and can be used. prototype:Function (socket) {}, the socket parameter is a net. Socket instance, which can also be obtained through the request. Connection member.

2.3 Close event, triggered when a connection is closed. Note: Connection and request-to-link can have multiple requests on a connection.

2.4 checkcontinue event: this event is triggered when the client receives a 100-continue request. If the client does not subscribe to this event, the server automatically replies 100-continue. when processing this event, if the client is allowed to continue sending data, use response. writecontinue. Otherwise, a specific error code is returned. event prototype:Function (request, response) {}. Note: When this event is triggered and processed, no request event will be generated.

2.5 connect and upgrade events. When a client requests a connect method (mainly used to establish a connection between the proxy server and the target server), the connect event is triggered. When a request for upgrade is sent, the upgrade event is triggered,If the server does not listen on these two events, the client's socket will be closed..

2.6 listen Function

 
Server. Listen (port, [hostname], [backlog], [callback])

Note that the default value of the backlog parameter is 511, And the callback parameter is called when the listener is successful.

2.7 two useful attributes

Server. maxheaderscount // indicates the maximum number of headers servers in the request sent by the client. timeout // The default timeout duration for client connections. A timeout event is triggered after the timeout period. If the timeout period is not handled, the timeout event is closed to the socket.

3, HTTP. serverresponse

This class is created by the server and passed in the second parameter of the Request event.

This class encapsulates the reply message to the client.

HTTP. serverresponse implements the writeable stream interface, so you can write data into it.

4. http. Request

This function is executed on the server to send a request, prototype: HTTP. in request (options, callback), it is critical to specify the parameters hostname, port, and path to options. When you want to execute a request to the specified URL, the URL module needs to be used for parsing, such as: URL. parse (dlinfo. dlurl ). host

5. http. Agent

The HTTP client uses an agent by default. You can use the agent: false option in the HTTP. Request function to disable the use of the agent.

AGENT: 1) agent. maxsockets indicates the maximum number of connections to a specified server. If many requests are sent to the same server, this value is very large. 2) The keepalive flag is enabled by default when you use the agent. The keepalive flag does not time out on the client, that is, the connection is immediately closed when no waiting request is sent.

6. http. clientrequest

The HTTP. clientrequest class is created using the HTTP. Request function, which indicates a request in progress.

HTTP. clientrequest implements the writeable stream interface, so you can write data into it.

Important Event: response indicates that an HTTP. incomingmessage parameter is provided in the event when a server response is triggered. You can obtain the specific response content through this parameter. If the server does not listen to the event, the server's reply will be discarded. The HTTP. incomingmessage parameter obtained when listening for response should read the data event at any readable time. Otherwise, the end event will not be triggered.

7. http. incomingmessage

HTTP. incomingmessage implements the readable stream interface, so you can write data into it.

HTTP. incomingmessage is used to read the data sent by the client in the request event of the server. In the client, it is used to read the data returned from the server in the response event.

Https:

The https server in node is implemented on the client, which is similar to HTTP.

Only some TLS parameters are added when server and request are created.

Net:

This module is TCP encapsulation in node.

 
Net. createserver ([Options], [connectionlistener]) is used to create a TCP server. You can then call listen to listen. The attribute allowhalfopen: false indicates whether the half-off state is allowed. If it is true, the system does not close itself when receiving the fin from the other party until the end function is called. buffersize indicates the number of buffer characters (non-bytes) of the socket in the node ). As the cache increases, the memory increases. Therefore, it can be used with pause and resume. Socket. setTimeout (timeout, [callback]) can be used to set the idle timeout of the Socket socket. setnodelay ([nodelay]) is used to disable Nagle AlgorithmAlgorithm. Socket. setkeepalive ([Enable], [initialdelay]) is used to execute the keepalive query. The initialdelay parameter indicates the interval from the last read/write data to the first send query packet. Net. isipv4 (input) provides a method to determine the IP address validity.

OS:

The OS module provides a lot of information about the operating system.

OS. endianness () // returns the large or small OS. platform () // platform OS. loadavg () // returns the system load for 1, 5, and 15 minutes. CPUs () // returns the cpu OS. networkinterfaces () // Network Interface OS. EOL // line break 

Path:

Provides some directory processing functions. The path. SEP path. delimiter attributes indicate the directory separator and delimiter respectively;

 
'Foo/BAR/Baz'. Split (path. SEP) // Returns ['foo', 'bar', 'baz']

Process:

Process is a global module in a node and does not require. It provides support for node process-related information query settings.

Event: exit, uncaughtexception (indicating that an unhandled exception exists. If the event is not processed, the process exits by default), and signal event (Name: Signal name, such as SIGINT ).

Input and Output: stdout and stderr (these two streams are synchronous when they are associated with a file or TTY, and asynchronous when they are associated with a pipeline ), stdin (by default, the stdin stream is paused and needs to be enabled using resume)

Process. argv indicates the parameter array during process running.

Process. nexttick (callback) is used to call callback in the next tick. It is mainly used to implement two functions: temporarily let the CPU do other processing to implement a real asynchronous callback function.

 
(The example is from the official document) // warning! Do not use! Bad unsafe hazard! Function maybesync (ARG, CB) {If (ARG) {CB (); return;} FS. stat ('file', CB);} maybesync (true, function () {Foo () ;}); Bar (); in the preceding example, when the first parameter "true" is passed to maybeync, the callback is called synchronously. Otherwise, the callback function is called asynchronously. Therefore, there is uncertainty. The correct method is as follows: "function definitelyasync (ARG, CB) {If (ARG) {process. nexttick (CB); // call callback in the next tick to ensure asynchronous callback return;} FS. stat ('file', CB );}

Process. umask ([mask]) is used to set the default mask of a process. It is used when a process creates a file.

Punycode:

Punycode encodes Unicode URLs into English to adapt to DNS queries.

For example:Penguin. Com, Converted to: Xn -- hoq754q. com using punycode

Readline:

This module can be used to read data from standard input for interaction.

VaR client = net. createconnection (1337); var RL = Readline. createinterface ({input: process. stdin, output: process. stdout}); RL. setprompt ('>'); // set the prompt RL. prompt (); // print the prompt RL. on ('line', function (line) {If (line = '0') {RL. close (); // close the client. end ();} else {client. write (line); RL. prompt (); // print the prompt }});

Querystring:

It is used to pack and parse the query parameters in a URL.

 
Querystring. stringify ({FOO: 'bar', Baz: ['qux', 'quux '], corge :''}) // returns 'foo = Bar & Baz = qux & Baz = quux & corge = 'querystring. stringify ({FOO: 'bar', Baz: 'qux'}, ';', ':') // returns 'foo: bar; Baz: qux'

Stream:

The stream module should be the core part of node. In versions 0.10 and earlier versions of readable, when the data event is not set, if resume is not called but switched to the old mode, the stream will be paused.

Readable abstract class

New stream. readable ([Options]), where options include highwatermark to indicate the maximum buffer size

Readable. Pipe (destination, [Options]) writes its own data to destination through a pipeline. The end parameter indicates whether to disable the destination when readable specifies the end. Readable. unpipe ([destination]) function.

Writable abstract class

New stream. writable ([Options]) where options include highwatermark indicating the maximum buffer size

Duplex abstract class (readable and writable)

New stream. Duplex (options)Allowhalfopen parameter indicates whether to allow the half-off status (TCP)

Transfer abstract class (it is a duplex, but the output is usually associated with the input in some way, such as zlib or encryption/Decryption)

Stringdecode:

This module is used to parse a buffer into a string. The class is in buffer. tostring (), but additional utf8 support is added.

Timer:

This module provides functions such as setTimeout and setinterval. These functions are global and can be used directly.

TLS/SSL:

Support HTTPS.

UDP/datax:

Supports UDP datagram.

URL:

The combination of URLs in the resolution function is implemented.

URL. parse (urlstr, [parsequerystring], [slashesdenotehost]) parses the given URL into an object.

URL. Resolve (from,)

 
URL. resolve ('/one/two/three', 'four ') //'/one/two/four 'URL. resolve ('HTTP: // example.com/','/one') // 'HTTP: // example.com/one'url.resolve ('HTTP: // example.com/one', '/two ') // 'HTTP: // example.com/two'

Util:

This module provides some basic functions, such as inheritance.

Util. Format (format, [...]) implements functions similar to printf

 
% S-string. % d-number (both integer and float). % J-JSON. %-single percent sign ('%'). This does not consume an argument.

Util. Inspect (object, [Options]) serializes an object into a string and returns it.

 
Util. isarray (object) util. isregexp (object) util. isdate (object) util. inherits (constructor, superconstructor) // sets the inheritance relationship. Note that the prototype of the constructor to be executed will be replaced. Therefore, if the construtor wants to modify the prototype, it must be defined after the function. You can also useConstructor. Super _ to access the parent class.

VM:

Provides access to VMS in V8.

Zlib:

As the name suggests.

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.