Nodejs Study Notes

Source: Internet
Author: User
Tags emit event listener readfile try catch

Hello Fuck is as follows:

Console.log (' Hello, fuck you, NodeJs '): # node helloworld.jshello, fuck you, NodeJs

Event:

Node. JS all asynchronous I/O operations are sent an event to the event queue upon completion, and the event is provided by the Eventemitter Object. The callback functions of Fs.readfile and Http.createserver mentioned earlier are implemented by Eventemitter.

Event.jsvar Eventemitter = require (' events '). Eventemitter;var event = new Eventemitter (), event.on (' some_event ', function () {    console.log (' some_event occurred. ');    setTimeout (function () {        event.emit (' some_event ');    },1000);}); SetTimeout (function () {    event.emit (' some_event ');},1000); console.log (' end? '); # node Event.js end?some_event occurred.some_event occurred.some_event occurred.^c

Nodejs constantly monitors the presence of active event listeners such as i/o, timer, etc., and once the event listener is found to be inactive, the Nodejs process Exits.

Module

The module is the basic part of Node. js, and the files and modules are one by one corresponding, in other words, a Node. js file is a module that may be JavaScript code, json, or compiled c/s extensions.

In the previous section, we used a similar var http=require (' http '), where HTTP is a core module that is internally implemented in C + + and externally using JavaScript for Encapsulation. After the module has been obtained through the Require function, the object can be Used.

create, Load Module

In Node. js, creating a module is very simple, because a file is a module, and the only thing we care about is how to get the module in other files, Node. JS provides exports and require two objects, where exports is the interface exposed by the module, and require is used for the external Gets the interface of a module, which is the exports object Returned.

Module.jsvar name;exports.setname=function (thename) {    name=thename;} Exports.sayhello=function () {    console.log (' Fuck you ' + name);} Getmodule.jsvar Mymodule=require ('./module ')//note here The./prefix is required because it is relative to the current working directory. Mymodule.setname (' mosmith '); mymodule.sayhello (); # node Getmodule.jshello mosmith

a single load , which is somewhat similar to creating an object, but actually differs from the object in nature, because require does not load the module repeatedly, that is, the modules obtained are the same regardless of how many times require are Called.

covering exports, Sometimes we just want to enclose an object in a module, for example:

Module.jsfunction Hello () {    var name;    This.setname=function (_name) {        this.name=_name;    }    This.sayhello=function () {        console.log ("Hello" + this.name);}    } Exports. Hello=hello;//override exports object//module.exports=hello;


Getmodule.js
var Hello = require ('./module.js '). Hello;
var hello=new Hello ();
Hello.setname (' Mosmith ');
Hello.sayhello ();

It should be noted that it is not possible to assign a value to a module.exports by exports direct Assignment. Exports is actually just a variable that points to the same object as the module.exports, which itself is released after the module execution ends, but module does not, so you can only change the provider by specifying MODULE.EXPORTS.

A package is a further step on the basis of a module, and Node. Js's package is similar to a C + + library or java/. Net's class library, which encapsulates a separate feature for publishing, updating, dependency management, and versioning, Node. JS implements the package mechanism according to the COMMONJS specification and develops NPM to address the release and acquisition requirements of the Package.

The Node. JS package is a directory that contains a json-formatted description file, package.json, A package that strictly conforms to COMMONJS should have the following Characteristics.

    1. Package.json must be in the top-level directory of the package
    2. Binary files should be in the bin directory
    3. JavaScript code should be in the Lib directory
    4. The document should be in the doc directory
    5. Unit tests should be in the test directory

however, Node. JS has less stringent requirements for packages, as long as the top-level directory is Package.json and conforms to some specifications. But it is best to conform to the NORM. When Node. JS calls a package, It first checks the main field in Package.json in the package as the interface module of the package, and if the Package.json or main field does not exist, it attempts to find Index.js or Index.node as the interface for the Package.

Package.json is a file specified by Commonjs to describe the package, the complete package should contain the following fields:

Name: the names of the packages must be unique, consisting of lowercase letters, numbers, and underscores, and cannot have Spaces.

Description: A brief description of the Package.

Version: a string that conforms to the semantic version recognition specification

Maintainer: maintainer array, first element to include name, email (optional), web (optional)

Contributors: the contributor array, in the same format as maintainer, the package author should be the first element of the Array.

Bugs the address where the bug was Submitted.

Licenses license array, Each element to contain the URL of type

An array of repositories warehouse managed addresses, each element containing the type (such as git), the URL (the address of the warehouse), and the Path (optional) field (as opposed to the warehouse).

Dependencies: a dependency of a package, an associative array consisting of the name and version number of the Package.

Here is an example of a package.json that conforms to the COMMONJS specification:

{    "name": "mypackage",    "description": "Sample Package for CommonJS." This package demonstrates the required elements of a CommonJS. ",    "version": "0.7.0",    "keywords": [        "package",        "example"        ],"maintainers": [    {        "name": "Bill Smith",        "email": "[email protected]",    }],"contributors": [    {        "name": "byvoid",        "web": "http://www.byvoid.com/"    }],"bugs": {    "mail": "[email protected]",    "web": "http://www.example.com/bugs"},"licenses": [    {        "type": "GPLv2",        "url": "http://www.example.org/licenses/gpl.html"    }],"repositories": [    {    ' Type ': ' git ',    "url": "http://github.com/BYVoid/mypackage.git"    }],"dependencies": {    "webkit": "1.2",    "ssl": {        "gnutls": ["1.0", "2.0"],        "openssl": "0.9.8"        }}}

NPM is a package management tool for Node. JS and has become the standard publishing platform for Node. JS Packages. Used for the release, propagation, and dependency control of Node. JS Packages.

NPM install/i package_name like to install Express

NPM Install Express or NPM I express

At the same time NPM will automatically resolve its dependencies, and get express-dependent Mime,mkdirp,qs connect and so On.

Local module and global mode

By default NPM will search and download the package from http://npmjs.org and install the package under the current Node_modules subdirectory. That is, local Mode.

In addition NPM can be installed in global mode (using the-g parameter), using the Method:

NPM install/i-g PackageName

however, It is important to note that the global schema may cause conflicts because other NODEJS programs may require a different version of the Package.

In local mode NPM does not register environment variables, while global mode takes note of environment variables and installs packages to system directories such as/usr/local/lib/node_modules, while the Bin field in the Package.json file contains files that are linked to/usr/ Local/bin. /usr/local/bin is defined by default in the PATH environment variable, so you can run a module like supervisor directly in the Command. however, The Global-mode package cannot be used by require because require does not search The/usr/local/lib/node_modules directory.

Create a global link

NPM provides a NPM link command that creates symbolic links between local and global packages, and we say that packages installed using global mode cannot be used with require, but this restriction can be bypassed through the NPM link command. Like what:

NPM Link Express

Here you can find a symbolic link to the global package that is installed in the Node_modules subdirectory. But this command cannot be used in Windows.

Debugging.

Node Debug debug.js

node--debug[=port] Script.js then use the IDE for remote debugging at another terminal node debug localhost:debug_port.

Global objects

JavaScript has a special object, called a global object, all of its properties can be accessed anywhere in the program, that is, global variables, in the Browser's javascript, usually window is a global object, And the global object in Node. js, global, is a property of the Globals object, all of which, except the global itself. In Node. js, we have direct access to objects through properties such as console, process, etc., which are global.

Global objects and global variables

Global's fundamental function is to host the global variables, as defined by ecmascript, which satisfies the following conditions.

    1. The outermost defined Variable.
    2. The properties of the global Object.
    3. Implicitly defined variables (variables that are not directly assigned to the same value are Defined)

When you define a global variable, the variable also becomes a property of the global object, and Vice Versa. It is important to note that in Node. js, you cannot define variables at the outermost layer, because all user code belongs to the current module, and the module itself is not the outermost context, it advocates the use of Var to define variables to avoid introducing global variables, because global variables pollute namespaces and increase the risk of code COUPLING.

Process

Process is a global variable, a property of the global object that describes the state of the current Node. JS process and provides a simple interface to the operating System. Writing some local command-line programs often requires dealing with it.

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.

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

Process.stdin is the standard input stream, initially paused, and wants to read data from the standard input you must resume the stream and manually write the Stream's event response Function. such as the Following:

The function of Process.nexttick (callback) is to set a task for the event loop, and Node. JS will call callback at the next event loop. Node. JS is suitable for I/O intensive applications, not compute-intensive applications, because 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.

function (data) {    process.nexttick (function() {        process.stdout.write (' do something very Time-consuming ');        Process.stdout.write (data);     });

The need for settimeout can also achieve a similar effect, but the settimeout efficiency is very low, the callback can not be executed in Time.

In addition to some of the more commonly used members above, there are process.platform,process.pid,process.execpath,process.memoryusage () and POSIX process signal response mechanisms.

Console

The console is used to provide control console Standard/error output:

Console.log () prints characters to the standard output stream and ends with a newline character. Console.log accepts several parameters, if there is only one argument, outputs the string form of this parameter, and if there are multiple parameters, the formatted output of the printf command similar to the C Language.

Console.log ("Helloworld"); = Helloworld
Console.log ("helloworld%s"); = = Helloworld%sconsole.log ("Helloworld%s", mosmith); = Helloworld Mosmith

Console.error () is the same as console.log, except that console.error () outputs to the standard error Stream.

The Console.trace () is used to output the current call stack to a standard error stream.

Common Tools Util

Util is the core module of Node. JS and 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, JavaScript object-oriented I'm prototype-based, Unlike common class-based classes, JavaScript does not provide the Language-level attributes of object inheritance, but is implemented through prototype replication, as explained in appendix a, where we will only describe the use of util.inerits, as shown here:

var util=require (' util ') function Base () {this.name= ' base ';    this.base=1991;    This.sayhello = function () {        console.log (' Hello ' + 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 ();//this was undefined in Sub//objsub.sayhello (); console.log (objsub);

Util.inspect

Util.inspect (object, [showhidden],[depth],[colors]) is a method that converts an arbitrary object to a string, usually for debugging and error output, at least one parameter, object, that is to be converted, ShowHidden is an optional parameter, if the value is true, it will output more parameters, depth represents the maximum number of recursive layers, if the object is complex, you can specify the number of layers to control how much output information, by default, two levels recursively, null in case of unlimited layers.

Event-driven Events

Events is the most important module for Node. js, and Node. JS itself relies on event Implementation-driven events, and it provides a unique interface. The events module is not just for user code interaction with the Node. JS downlevel event loop, but is also almost dependent on all Modules.

Event emitter

The events module provides only one object, Events. eventemitter, the core of Eventemitter is the encapsulation of event launch and event listener Functionality. Eventemitter Each event consists of an event and several parameters, the event name is a string, usually expresses a certain semantics, for each event, Eventemitter supports a number of event listeners, when the event is launched, the event listener registered to this event will be called sequentially, The event arguments are passed as callback Functions.

 //eventemittertest.js 
var events=require (' Events ' function (arg1,arg2) {console.log ( ' listener1 invoked ' ' someevent ', function (arg1, Arg2) {console.log ( ' listener2 invoked ' ,arg1,arg2);}); Emitter.emit ( ' someevent ', ' argument1 ', 2017 2017listener2 invoked argument1
    • Eventemitter.on (event, Listener) Registers a listener for the specified event, accepting a string event and a callback function listener.
    • Eventemitter.emit (event, [arg1], [arg2], [...]) launches event, passing several optional parameters to the event Listener's parameter Table.
    • 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

Error Event

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. therefore, we generally need to set the listener for the object that will emit the error event, and avoid the whole program crashing after encountering the Errors. Like what:

varEvents = Require (' events ');varEmitter =NewEvents. Eventemitter (); Emitter.emit (' Error '), The following error is displayed at run time: node. js:201ThrowE//process.nexttick error, or ' error ' event on first tick^error:uncaught, Unspecified' Error 'event.at eventemitter.emit (events.js:50:15) at Object.<anonymous> (/home/byvoid/error.js:5:9) at Module._compile (module.js:441:26) at Object. JS (module.js:459:10) at Module.load (module.js:348:31) at Function._load (module.js:308:12) at Array.0 (module.js:479:10) at Eventemitter._tickcallback (node. js:192:40)

Inherit Eventemitter

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. Why do you do this? there are two reasons. first, an object with an entity function implements the semantics of the event, and the listener and the launch 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.

File System FS

FS module is a closed file operation, it provides file read, write, rename, delete, traverse directory, link and other POSIX file operations, Unlike other modules, the FS module all operations have synchronous and asynchronous two versions, such as the function of reading the contents of the file is asynchronous Fs.readfile () There are also synchronous fs.readfilesync.

Fs.readfile (filename, [encoding], [callback (err,data)]) is the simplest function to read a file, it accepts a required parameter filename, and if encoding is not provided, it is opened in binary mode If Encoding,data is specified, it is a parsed string.

Fs.readfilesync is a synchronous version, it does not have a callback parameter, data is obtained by the return value, and the error needs to be caught by a try Catch.

Fs.open (path, flag, [mode], [callback (err,fd])] is the encapsulation of the POSIX open function, similar to C and fopen, it has two required parameters, path is a file path, and flag is the way to open the file, The mode parameter is used to assign permissions to the file when the file is created, default is 0666, the callback function passes an error parameter, and a file descriptor FD

Fs.read (fd,buffer, offset, length, position, callback (err, byteread, buffer)] are the POSIX read function closed, compared to fs.readfile, It provides a lower-level interface, The Fs.read function is to read data from the specified file descriptor fd and write to the buffer object specified in buffer, offset is the write offset of buffer, length is the number of bytes to read from the file, position is the starting position of the file read, and if the value of position is null, the is read from the position of the current file pointer, and the callback function passes Byteread and buffer, respectively, representing the number of bytes read and the buffers Object.

HTTP Module

The Node. JS Standard library provides an HTTP module in which 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 requests to an HTTP server, such as implementing Pingback 1 or content fetching

http. Server

http. Server is an HTTP server object in the HTTP module, All HTTP protocol-based systems, such as Web sites, social applications, and proxy servers that are made with Node. js, are based on http.server, which provides an API with a low level of encapsulation, only flow control and simple message parsing, and all the high-level functions are implemented through its interfaces.

Nodejs Study Notes

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.