1. Core modules
The core module is the heart of node. JS and consists of a few streamlined libraries that provide a basic API.
2. Global objects
Global All of the global variables are their properties. Its fundamental function is to host a global variable.
3. Global variables
1.process: An object that describes the process state of the current node. JS, providing a simple interface to the operating system.
Method process.argv command-line parameter array three parameters 1.node 2. script file name 3. Run parameters
1.process.stdout: The standard output stream, typically used by Console.log (), prints characters to the standard output, while Process.stdout.write provides a lower-level interface.
2.process.stdin: The initial state of the standard input stream is paused to read data from a standard input, you must restore the stream and manually
Writes the event corresponding function for the stream.
Process.stdin.resume ();//Reply stream
Process.stdin.on (' Data ', function (data) {//listener event corresponding
Process.stdout.write (' read from console: ' + data.tostring () ');//Return input
});
In Terminal input Andy
In terminal output read from Console:andy
If you do not exit the CTRL + C event will always be in the appropriate state
3.process.nexttick (callback): Sets a task for the event loop that node. JS responds to in the next event loop Si Cho
with callback;
PS: Because the node. JS process has only one thread, only one event is executed at any time, if this event
Takes a lot of CPU time, and the next event in the event loop takes a long wait, so a principle of node. js
is to try to shorten the execution time for each event. Process.nexttick provides a tool that can put complex
Work is broken up into smaller events.
function A (args, callback) {
b (args);
Callback ();
}
A (function C () {
D ();
});
Suppose A, B is a two time-consuming program.
Execution process: 1. Execute a, pass C as parameter to args
2. Execute B, where the argument is function c
3. Execute C
4. Execution D
5. Execute callbacks
Rewrite with Process.nexttick
function dosomething (args, callback) {
somethingcomplicated (args);
Process.nexttick (callback);
}
DoSomething (function onEnd () {
Compute ();
});
The rewritten program splits the time-consuming operation into two events, reducing the execution times of each event and increasing the speed of the event accordingly. Do not use settimeout (fn,0) instead, because this is much less efficient.
4. See other API documentation
2.console: Used to output characters to standard output stream or standard error stream
1.console.log () prints characters to the standard output stream with line breaks
2.console.error () outputs characters to the standard error stream with line breaks
3.console.trace () outputs the current call stack to the standard error stream
4. Common Tools
1.util: A core module that provides a common set of functions.
1.util.inherits (constructor,superconstructor) is a function that implements prototype inheritance between objects. Sub-class Relay
The class of the bearing. JS does not provide the language-level attributes of object inheritance, but is implemented through prototype replication.
var util = require (' util ');//Request Module
function Base () {//base constructor
this.name = ' base ';
This.base = 1991;
This.sayhello = function () {
Console.log (' Hello ' + this.name);
};
}
Base.prototype.showName = function () {//prototype method ShowName
Console.log (this.name);
};
function Sub () {//sub constructor
this.name = ' Sub ';
}
Util.inherits (Sub, Base); Sub inherits the prototype of base
var objbase = new Base (); Instantiation of
Objbase.showname (); Base
Objbase.sayhello (); Hello Base
Console.log (objbase);//base{name: ' Base ', Base:1991,sayhello:[function]}
Prototype properties are not output by Console.log () as an object's property
var objsub = new Sub ();
Objsub.showname ();//sub
Objsub.sayhello ();//error because sub is only a prototype that inherits base, SayHello is not in prototype
Console.log (objsub); Sub{name: ' Sub '}
2.util.inspect (Object,[showhidden],[depth],[colors]) is a method that converts an arbitrary object to a string.
Typically used for debugging and error output.
Parameters: Unique Required argument object: The object to be converted
ShowHidden defaults to False if True will output more information
Depth indicates that the maximum number of levels of recursion defaults to 2 levels null is unrestricted
Colors if the value is true the output format will be encoded in ANSI color, more beautiful
3. Other Search API documentation
5. Event-driven events: one of the most important modules, none of which is the cornerstone of node. JS programming. Not only for user code with node. JS under
The interaction of Layer event loops is also almost dependent on all modules.
The 1.events module provides only one object: events. Eventemitter
1.events. Eventemitter: Encapsulation of event launch and event listener functionality.
Events. Each event of the Eventemitter consists of an event name and several parameters. For each event, support for several
An event listener. When an event is emitted, the event listener registered to the event is called sequentially, and the event arguments are
callback function parameter passing.
var events = require (' events ');//Request Module
var emitter = new events. Eventemitter ();//Instantiation of Object
Emitter.on (' Someevent ', function (Arg1, arg2) {//Monitor Someevent
Console.log (' Listener1 ', arg1, arg2);//Execute callback
});
Emitter.on (' Someevent ', function (Arg1, arg2) {//Monitor Someevent
Console.log (' Listener2 ', arg1, arg2);//Execute callback
});
Emitter.emit (' someevent ', ' Byvoid ', 1991);//Trigger Event
Events. Eventemitter Common API
1.eventemitter.on (Event,callback);
Registers a listener for the specified event, accepts a string (event name), and a callback function
2.eventemitter.emit (Event,[arg1],[arg2],[arg3] ...); Triggering event events,
and pass in several parameters to the event listener's parameter table
3.eventemitter.once (Event,callback) is different from on, triggering at most once, after triggering
Immediately dismiss the listener.
4.eventemitter.removelistener (Event,listener) removes a listener for the specified event
Listener must be a listener that has already been registered for this event.
5.eventemitter.removealllistener ([Event]); Remove all listeners from all events,
If event is specified, all listeners for the specified event are removed.
6.error when error is fired, eventemitter rules if there is no response to the listener, NODE. JS will treat it as an exception, exit the program and print the call stack. We typically set up listeners for the object that will emit the error time. Avoid encountering errors after the entire program crashes.
var events = require (' events ');
var emitter = new events. Eventemitter ();
Emitter.emit (' error ');
PS: Most of the time, the eventemitter is not used directly, but it is inherited from the object, including FS,. NET, HTTP,
As long as the core module of the module supporting the event is the Eventemitter subclass.
Cause 1: Objects with an entity function implement events that conform to semantics, and the listener and launch of an event should be a method of an object.
2:js is based on the reason that partial inheritance is supported, and inheriting Eventemitter does not disrupt the original inheritance relationship of the object.
2. File System FS
The FS module is the encapsulation of the file operation, which provides the file read, write, rename, delete, traverse directory, connection and other POSIX
File system operations. All operations of FS provide two versions of both synchronous and asynchronous.
1.fs.readfile (Filename,[encoding],[callback (Err,data)).
The only required parameter filename to read
Character encoding of the encoding file
Callback callback function
Two parameters 1.err indicates there is no error firing
2.data file Contents If you specify Encoding,data as the parsed string, the
The binary data represented in buffer format.
var fs = require (' FS ');
Fs.readfile (' Content.txt ', function (err, data) {
if (err) {
Console.error (ERR);
} else {
Console.log (data);
}
});
Binary form Output
var fs = require (' FS ');
Fs.readfile (' Content.txt ', ' utf-8 ', function (err, data) {
if (err) {
Console.error (ERR);
} else {
Console.log (data);
}
});
UTF encoded form output
NODE. JS usually has and has only one callback function. The first parameter in the callback function is actually error, the rest of the arguments
is the other returned content, and if no error occurs, the value is null or undefined. If there are errors, error is usually an instance of the Error object.
2. Sync: Fsreadfilesync (Filename,[callback (err,filedata))
3.fs.open (Path,flags,[mode],[callback (Err, Filedata)]) is the encapsulation of the POSIX open function.
Required two parameters path to file
Flags can be the following values
R read-only
r+ read-write
W write-only, non-existent is created.
W+ Read-write, not present, is created.
A append mode is open and does not exist when it is created.
A + is opened with read Append mode and is created if it does not exist.
mode is used to assign permissions to files when creating files default 0666
4.fs.read (Fd,buffer,offset,length,position,[callback[err,bytesread,buffer]) The
is the encapsulation of the POSIX read function. The implementation reads the data from the specified file descriptor FD and writes to the buffer pointer to the
object. Offset is the offsets given in buffer. Length is the number of bytes to read from the file. Position is the starting position of the file read and, if NULL, is read from the position of the current file pointer. The Bytesread,buffer table passed by the callback function represents the number of bytes read and the buffer object.
var fs = require (' FS ');
Fs.open (' Content.txt ', ' R ', function (err, FD) {//Open file as read-only
if (err) {
Console.error (ERR);
Return
}
var buf = new Buffer (8);
Fs.read (FD, buf, 0, 8, NULL, function (err, bytesread, buffer) {
if (err) {
Console.error (ERR);
Return
}
Console.log (' bytesread: ' + bytesread);
Console.log (buffer);
})
});
Generally speaking, there is no need to take such a method, very troublesome.
5. See the documentation for other APIs.
6.http Server
1.http. The server is an HTTP server object in the HTTP module, with all the HTTP protocol-based systems of node. js. Providing only flow control and simple message parsing, all high-level functions are implemented through its interfaces,
Httpserver.js
var http = require (' http ');//
Http.createserver (function (req, res) {//Create server
Res.writehead ($, {' Content-type ': ' text/html '});
Res.write (' Res.end (' <p>hello world</p> ');//End and send
}). Listen (3000);//Listener Port number
Console.log ("HTTP server is listening at Port 3000.");
1.request, this event is triggered when a client request arrives. Available in two parameter req,res,
HTTP, respectively. An instance of Serverrequest and http.serverresponse that represents the request and response information.
2.connection: When the TCP connection resumes, the event is triggered, providing a parameter socket for the Net.socket instance
。 The granularity of the connection is greater than the request because the client may be within the same connection in the keep-alive mode
Multiple requests.
3.close: The event is triggered when the server is down. Note Not when the user connection is disconnected.
4. Other checkcontinue, upgrade, Clienterror, etc.
The most commonly used request,http creates a shortcut. Http.createserver ([Requestlistener]), create a
HTTP server and use Requestlistener as the listener function for the request event.
The code above is actually
Httpserver.js
var http = require (' http ');
var server = new http. Server ();
Server.on (' request ', function (req, res) {//Register request Event
Res.writehead ($, {' Content-type ': ' text/html '});
Res.write (' Res.end (' <p>hello world</p> ');
});
Server.listen (3000);
Console.log ("HTTP server is listening at Port 3000.");
2.http. Serverrequest:http the requested information. by HTTP. Server request event sent as the first parameter passed
, HTTP requests can generally be divided into two parts: the request header (Requestheader) and the request body (requestbody).
Three events are used to control the transfer of the request body:
1.data: Triggers an event when the request body data is brought. The event provides a parameter chunk that represents the accepted data,
If the event is not being monitored, then the request body will be discarded and the event can be called multiple times.
2.end: When the request body data transfer is complete, the event is triggered and there will be no more data coming
3.close: When the user's current request ends, the trigger event, unlike end, also calls close if the user forces the transfer to terminate.
4. Other properties See API documentation
3. Get the GET Request content
Because the GET request is embedded directly in the path, the URL is the full request path, including? Later sections, so you can manually parse the following contents as parameters for get requests. The parse function in the URL module provides this functionality.
Httpserverrequestget.js
var http = require (' http ');//Request Required Module
var url = require (' URL ');
var util = require (' util ');
Http.createserver (function (req, res) {
Res.writehead ($, {' Content-type ': ' Text/plain '});
Res.end (Util.inspect (Url.parse (Req.url, True));//!!
}). Listen (3000);//input path in localhost:3000
Take Localhost:3000/uesr?name=andy&[email protected] For example:
return: {
Search: '? Name=andy&[email protected] ',
Query:{name: ' Andy ', email: ' [email protected] '},//get requested content
Pathname: '/user ',
Path: '/uesr?name=andy&[email protected] ',
HREF: '/uesr?name=andy&[email protected] '
}
4. Get Post Content
The contents of the POST request are all in the request body.
Httpserverrequestpost.js
var http = require (' http ');
var querystring = require (' querystring ');
var util = require (' util ');
Http.createserver (function (req, res) {
var post = ";//define a post for staging the request body content
Req.on (' Data ', function (chunk) {
Post + = chunk;
});
Req.on (' End ', function () {
Post = Querystring.parse (POST);
Res.end (Util.inspect (POST));
});
}). Listen (3000);
Through the Req Data event listener function, each time a request body is received, it is added to the post. After the end is triggered,
The post is parsed into real post data via Querystring.parse and then returned to the client. (The actual project cannot
So used, because of serious efficiency and safety problems);
5.http. Serverresponse: The information returned to the client determines the results that the user can eventually see. It is also by
http. The server's request event is sent as a second parameter, referred to as response or Res.
Three parameters
1.response.writehead (Statuscode,[headers]): Sends a response header to the requesting client.
StatusCode is an HTTP status code
200: Request succeeded
404: Not Found
Wait a minute
Headers: An object that resembles an associative array that represents each property of the response header. The function can be used up to one time within a request and automatically generates a response header if not called.
2.response.write (data,[encoing]): Sends the response content to the requesting client.
Data is a buffer or string that represents the content to send.
If data is a string, then you need to specify encoding to indicate the encoding, and the default is UTF-8
You can call Response.Write multiple times before calling Response.End.
3.response.end ([data],[encoding]): Ends the response, informing the client that all the sends have been completed. When
The function must be called once when all the content to be returned has been sent. Two optional parameters if you want to write the
Word Usage with data
6.HTTP Client
The HTTP module provides two functions http.request and http.get, which function as a client to initiate a request to an HTTP server
Http.request (options,callback) initiates an HTTP request.
Options: An object that resembles an associative array that represents the requested parameter
Common parameters
Host: The domain name or IP address of the requesting web site
Port: Ports requested, default is 80
Method: Request methods, default to get
Path: The relative root path of the request, default is/.
Headers: An object that resembles an associative array, the header content of the request
Callback: callback function for request
Pass a parameter to HTTP. Examples of Clientrespongse
Http.request returns an instance of a Http.clientrespongse.
Httprequest.js
var http = require (' http ');
var querystring = require (' querystring ');
var contents = querystring.stringify ({//Convert object to String
Name: ' Byvoid ',
Email: ' [email protected] ',
Address: ' Zijing, Tsinghua University ',
});
var options = {
Host: ' Www.byvoid.com ',
Path: '/application/node/post.php ',
Method: ' POST ',
Headers: {
' Content-type ': ' application/x-www-form-urlencoded ',
' Content-length ': contents.length
}
};
var req = http.request (options, function (res) {
Res.setencoding (' UTF8 ');
Res.on (' Data ', function (data) {
Console.log (data);
});
});
Req.write (contents);
Req.end ();//This Must have
1.http.get (options,callback) http.request simplified version, the difference is http.get automatic
The request method is set to get request, nor does it need to set req.end ();
1.http. Clientrequest is an object produced by Http.request and Http.get, representing an already generated
and an HTTP request is in progress. Provides a response event, which is the binding object of the callback function specified when the second parameter is Http.get or http.request, and we can explicitly bind the listener function of this event.
Httpresponse.js
var http = require (' http ');
var req = Http.get ({host: ' www.byvoid.com '});
Req.on (' response ', function (res) {
Res.setencoding (' UTF8 ');
Res.on (' Data ', function (data) {
Console.log (data);
});
});
http. Clientrequest provides the write and end functions for sending the request body to the server, usually for post, and
Put, and so on. End must be used after
Request.abort (): Terminating a sent request
Request.settimeout ([Callback],timeout)
There are other parameters to look at the API
2.http. Clientresponse
Provides three events when data arrives to trigger a parameter chunk represents the received data
Triggered when end transfer ends
Trigger at end of close connection
http. Some properties of clientresponsed are used to represent the requested result status
StatusCode 200, 404, 500, etc.
Httpversion Protocol version
Headers HTTP request Header
Trailers Request Tail
http. Special functions of the clientresponsed
Response.setencoding
Response.pause pause to receive data and send events for easy download
Response.resume recovering from a paused state
NODE. JS Development Guide Learning Note 2