node. js "5" core module

Source: Internet
Author: User
Tags emit event listener posix readfile

Notes from the node. JS Development Guide Byvoid

4th Chapter node. JS Core Module
4.1. Global objects
The global object in node. js is globals, and all global variables (except the global itself) are properties of the global object. We have direct access to objects in node. js that are typically global properties, such as console, process, and so on.

Always use Var to define variables to avoid introducing global variables, because global variables pollute namespaces and increase the risk of code coupling.

Process is an object that describes the state of the current node. JS process and provides a simple interface to the operating system.

PROCESS.ARGV is an array of command-line arguments, the first element is node, the second element is the script file name, and the third element starts with each element being a run parameter.

Process.stdout is the standard output stream, which is usually the console.log () that we use to print characters to the standard output, while the Process.stdout.write () function provides a lower-level interface.

Process.stdin is the standard input stream, initially paused, and to read from the standard input, you must resume the stream and manually write the stream's event response function.

The function of Process.nexttick (callback) is to set a task for the event loop, and node. JS calls callback the next time the event loops over the response.
A node. JS process has only one thread, so there is only one event executing at any moment. If this event takes up a significant amount of CPU time, the next event in the event loop will have to wait long, so one of the programming principles of node. JS is to minimize the execution time of each event. Process.nexttick () provides a tool to break up complex work and turn it into smaller events. For a tool like this that can put complex work

The process also shows methods such as Process.platform, Process.pid, Process.execpath, Process.memoryusage (), and the POSIX process signal response mechanism. Interested readers can visit http://nodejs.org/api/process.html for more information.

The console is used to output characters to the standard output stream (STDOUT) or standard error stream (stderr).

Console.log (): Prints characters to the standard output stream and ends with line breaks. If there are multiple parameters, it is output in a format similar to the C-language printf () command. The first argument is a string, and if there are no arguments, only one line break is printed.

Console.error (): Same as Console.log () usage, just output to standard error stream.

Console.trace (): Outputs the current call stack to the standard error stream.

4.2. Common Tools Util
Util is a node. JS Core module that provides a collection of commonly used functions to compensate for the lack of the functionality of core JavaScript too thinly.

Util.inherits (constructor,superconstructor) is a function that implements prototype inheritance between objects.

var util = require (' util '), function Base () {this.name = ' base '; this.base = 1989;this.sayhello = function () {Console.log (' H Ello ' + this.name);};} Base.prototype.showName = function () {console.log (this.name);}; function Sub () {this.name = ' Sub ';} Util.inherits (Sub, Base), var objbase = new Base (); Objbase.showname (); Objbase.sayhello (); Console.log (objbase); var Objsub = new Sub (); Objsub.showname ();//objsub.sayhello (); Console.log (objsub);/* Run Result: Basehello base{name: ' Base ', base:1991, SayHello: [Function]}sub{name: ' Sub '} */

The sub inherits only the functions defined by base in the prototype, and the base property and the SayHello function created inside the constructor are not inherited by Sub. Also, properties defined in the prototype are not output by Console.log as an object's property.

Util.inspect (Object,[showhidden],[depth],[colors]) is a method that converts any object to a string, typically for debugging and error output. It accepts at least one parameter, object, which is to be converted.
ShowHidden is an optional parameter, and if the value is true, more hidden information will be output.
Depth represents the maximum number of recursive layers, and if the objects are complex, you can specify the number of layers to control how much output information is. If you do not specify depth, the default is 2 levels, which is specified as null to completely traverse the object with an unlimited number of recursive layers.
If the color value is true, the output format will be encoded in ANSI color, typically used to display a more beautiful effect on the terminal.

In particular, Util.inspect does not simply convert an object to a string, even if the object defines the ToString method.

var util = require (' util '), function person () {this.name = ' Ichenxiaodao '; this.tostring = function () {return this.name;};} var obj = new Person (), Console.log (Util.inspect (obj)), Console.log (Util.inspect (obj), true);/* Run Result: {name: ' Ichenxiaodao ', ToString: [function]} {name: ' Ichenxiaodao ',  tostring:   {[function]     [length]: 0,     [ Name]: ",     [arguments]: null,     [caller]: null,     [prototype]: {[constructor]: [Circular]}}} */

In addition to the several functions we have described above, Util also provides Util.isarray (), Util.isregexp (), Util.isdate (), Util.iserror () Four types of test tools, and Util.format (), Tools such as Util.debug (). Interested readers can visit http://nodejs.org/api/util.html for more information.


4.3. Event Driven Events
Events is the most important module of node. js, and there is no "one" because node. JS itself is an event schema, and it provides a unique interface, so it is the cornerstone of programming for node. JS events. The events module is not only used for user code interaction with the node. JS downlevel event Loop, but is also almost dependent on all modules.

The events module provides only one object: events. Eventemitter. The core of Eventemitter is the encapsulation of event launch and event listener functionality. Each event of the Eventemitter consists of an event name and several parameters, which is a string that usually expresses a certain semantics. For each event, Eventemitter supports a number of event listeners. When an event is emitted, the event listener registered to the event is called sequentially, and the event arguments are passed as a callback function parameter.
var events = require (' events '); var emitter = new events. Eventemitter ();//Register Event//Specify event register a listener, accept a string event and a callback function listener. Emitter.on ("Someevent", Function (Arg1, arg2) {console.log ("Listener1", Arg1, arg2);}); /Register Event Emitter.on ("Someevent", Function (Arg1, arg2) {console.log ("Listener2", Arg1, arg2);}); /launch events//launch event, passing several optional parameters to the event listener's parameter table. Emitter.emit ("Someevent", "Ichenxiaodao", 1989);/* Run Result: Listener1 ichenxiaodao 1989listener2 Ichenxiaodao 1989 */
Eventemitter.once (Event,listener) registers a single listener for the specified event, that is, the listener is fired at most once, and the listener is released immediately after the trigger.
Eventemitter.removelistener (Event,listener) removes a listener for the specified event, listener must be a listener that the event has already registered.
Eventemitter.removealllisteners ([Event]) removes all listeners for all events and, if specified, removes all listeners for the specified event.
See http://nodejs.org/api/events.html For more detailed API documentation.

Eventemitter defines a special event error, which contains the semantics of "error", and we usually emit an error event when we encounter an exception. When error is fired, eventemitter specifies that if there is no response 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 event, to avoid the entire program crashing after encountering errors.
var events = require (' events '); var emitter = new events. Eventemitter (); Emitter.emit (' error ');/* Run Result: events.js:74        throw TypeError (' uncaught, unspecified ' error ' event. ');              ^typeerror:uncaught, unspecified "error" event.    At TypeError (<anonymous>) at    Eventemitter.emit (events.js:74:15) at    object.<anonymous> (/users/ Cdz/workspace/my-node/nodejs_dev_guide_book/4/error.js:5:9) at    module._compile (module.js:456:26)    at Object.module._extensions. JS (module.js:474:10) at    module.load (module.js:356:32) at    function.module._load (module.js:312:12)    at Function.Module.runMain (module.js:497:10) at    startup (node.js:119:16) at    node.js:906:3 */
Most of the time we don't use eventemitter directly, but we inherit it from the object. Including FS, NET, HTTP, as long as the core modules that support event response are Eventemitter subclasses.

The reason is that: first, objects with an entity function implement events that conform to semantics, and the listener and launch of an event should be the method of an object. Secondly, the object mechanism of JavaScript is based on prototype, supporting partial inheritance, inheriting Eventemitter does not disturb the original inheritance relationship of the object.

4.4. File System FS
FS module is the encapsulation of file operation, it provides the file read, write, rename, delete, traverse directory, link and other POSIX file system operation. Unlike other modules, all operations in the FS module provide asynchronous and synchronized two versions, such as functions that read the contents of a file with asynchronous Fs.readfile () and synchronous Fs.readfilesync ().

Fs.readfile (Filename,[encoding],[callback (Err,data)) is the simplest function to read a file. It takes a required parameter, filename, to indicate the name of the file to read. The second parameter, encoding, is optional, which represents the character encoding of the file. Callback is a callback function that is used to receive the contents of a file. If you do not specify encoding, then callback is the second parameter. The callback function provides two parameters, err and data,err, indicating that no error occurred and that data is the file content. If Encoding,data is specified as a parsed string, data will be binary data in the form of buffer.

The asynchronous programming interface of node. JS is used to take the last parameter of a function as a callback function, usually a function with only one callback function. The callback function is the first of the actual arguments is err, and the rest of the arguments are the other returned content. If no error occurs, the value of ERR will be null or undefined. If an error occurs, err is usually an instance of the Error object.

Fs.readfilesync (Filename,[encoding]) is a version of Fs.readfile synchronization. It accepts the same parameters as the Fs.readfile, and the contents of the read file are returned in the form of a function return value. If an error occurs, FS throws an exception, and you need to use try and catch to catch and handle the exception.

Fs.open (Path,flags,[mode],[callback (ERR,FD))
Fs.read (Fd,buffer,offset,length,position,[callback (Err,bytesread,buffer))

4.5. HTTP Server and Client
The node. JS Standard library provides an HTTP module that encapsulates an efficient HTTP server and a simple HTTP client. http. Server is an event-based HTTP server whose core is implemented by the node. JS downlevel C + + section, and the interface is packaged in JavaScript for high performance and simplicity. Http.request is an HTTP client tool that initiates a request to an HTTP server.
var http = require (' http '); Http.createserver (function (req, res) {Res.writehead ($, {' Content-type ': ' text/html '}); Res.write (' 
Http.createserver creates an instance of Http.server and takes a function as an HTTP request handler function. This function accepts two parameters, namely the Request object (req) and the Response object (RES).

http. Server is an event-based HTTP server, all requests are encapsulated as separate events, and developers only need to write a response function on its events to implement all the functions of the HTTP server. It inherits from Eventemitter

The preceding example shows an explicit implementation method:
var http = require (' http '); var server = new http. Server (); Server.on (' Request ', function (req, res) {Res.writehead ($, {' Content-type ': ' text/html '}); Res.write (' < H1>node.js
http. Serverrequest is the message of HTTP requests and is the focus of the backend developers. It is generally by
http. The server's request event is sent as the first parameter, usually referred to as a request or req.

Because the GET request is embedded directly in the path, the URL is the complete request path, including the following section, so you can manually parse the following contents as parameters of the GET request. The parse function in the URL module of node. JS provides this functionality.
var http = require (' http '), 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 (true)));}). Listen (3000);/* Access: Http://127.0.0.1:3000/user?name=ichenxiaodao&[email protected] Back: {protocol:null,  Slashes:null,  auth:null,  host:null,  port:null,  hostname:null,  hash:null,  search: '? name =ichenxiaodao&[email protected] ',  query: {name: ' Ichenxiaodao ', email: ' [email protected] '},  pathname: '/ User ',  path: '/user?name=ichenxiaodao&[email protected] ',  href: '/user?name=ichenxiaodao&[email Protected] '}*/
Manually parse the POST request body.
var http = require (' http '), var querystring = require (' querystring '), var util = require (' util '); Http.createserver ( Function (req, res) {var post = '; Req.on (' Data ', function (chunk) {post + = chunk;}); Req.on (' End ', function (chunk) {post = Querystring.parse (post); Res.end (Util.inspect (POST));}). Listen (3000);
http. Serverresponse is the information returned to the client, which 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, generally referred to as response or Res.

http. The Serverresponse has three important member functions:
Response.writehead (Statuscode,[headers])
Response.Write (Data,[encoding])
Response.End ([data],[encoding])

The HTTP module provides two functions http.request and http.get, which function as a client to initiate a request to an HTTP server.
var http = require (' http '); var querystring = require (' querystring '); var contents = querystring.stringify ({name: ") Ichenxiaodao ", Email:" [email protected] ", Address:" Shanghai "}); 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 (' utf-8 '); Res.on (' Data ', function (data) {Console.log (data);}); Req.write (contents); Req.end ();
The Http.get (options,callback) HTTP module also provides a more convenient way to handle get requests: Http.get. It is a simplified version of Http.request, the only difference being that Http.get automatically sets the request method to a GET request and does not require a manual call to Req.end ().

http. Clientrequest is an object produced by Http.request or http.get that represents an HTTP request that has been generated and is in progress. It provides a response event, which is the binding object of the callback function specified by the second parameter of Http.request or Http.get.

http. Clientrequest, like Http.serverresponse, also provides the write and end functions for sending the request body to the server, typically for post, put, and so on. After all writes have been completed, the End function must be called to notify the server, otherwise the request is invalid.

http. Clientresponse, similar to Http.serverrequest, provides three event data, an end
And close, which are triggered at the end of the data arrival, transfer end, and connection, where the data event passes a parameter, chunk, that represents the received information.


Expand reading: http://nodejs.org/api/index.html



Document Information

    • Copyright Disclaimer: Free Reprint-Non-commercial-non-derivative-retain attribution | Creative Commons by-nc-nd 3.0
    • Original URL: http://blog.csdn.net/cdztop/article/details/33473299
    • Last modified: June 23, 2014 01:04

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.