Notes from the node. JS Development Guide Byvoid
Chapter 1th Introduction to Node. js
node. JS is a development platform that allows JavaScript to run on the server, making JavaScript a world-class citizen of the scripting language and serving PHP, Python, Perl, and Ruby on an equal footing.
node. JS can serve as a server to users, compared to PHP, Python, rubyonrails, it skips the Apache, Nginx and other HTTP servers, directly facing the front-end development.
node. js can also invoke code from C + + to take advantage of many of the existing library functions, or to implement a very high performance-demanding section in C + +.
The biggest feature of node. JS is the asynchronous I/O and event-driven architecture design. For highly concurrent solutions, the traditional architecture is a multithreaded model that provides a system thread for each business logic to compensate for the time overhead of synchronous I/O calls through system thread switching. node. JS uses a single-threaded model, with asynchronous requests for all I/O, avoiding frequent context switching. node. JS maintains an event queue during execution, the program enters the event loop at execution time, waits for the next event to arrive, and each asynchronous I/O request is pushed to the event queue for processing by the program process.
"Figure" node. JS Schema
2nd. Installing and configuring node. js
node. JS Development Environment Setup (Windows, Linux&mac)
node. JS Multi-Version Manager
Chapter 3rd Quick start of node. js
$node-E "console.log (' HelloWorld ');"
HelloWorld
We can execute the statement that we want to execute as a node-e parameter directly.
REPL (Read-eval-printloop), which is the input-evaluation-output loop. Running the parameterless node will launch a JavaScript interactive shell. If you execute a function, REPL also shows the return value of the function below. If you enter an incorrect instruction, REPL will immediately display the error and output the call stack. At any time, press CTRL + C two times to launch node. JS's Repl mode.
"Figure" node. js and PHP architecture
node. js only parses the script file the first time it is referenced to a part, and then accesses the memory directly, avoiding repeated loading. Supervisor can help you implement this feature by monitoring your code changes and automatically restarting node. js. The easy way to use it is to first use NPM to install Supervisor:
$npminstall-gsupervisor
Start app.js with the Supervisor command:
$supervisorapp. js
"Figure" Multi-threaded synchronous I/O
"Figure" single-threaded asynchronous I/O
Single-threaded event-driven asynchronous I/O is better than traditional multi-threaded blocking I/O? In short, asynchronous I/O is less of a multithreaded overhead. For the operating system, the cost of creating a thread is very expensive, it needs to allocate memory, scheduling, while the thread switch to perform memory paging, the CPU cache is emptied, switching back to the time to re-read information from memory, destroying the data locality.
3.1 Callback function "code" Readfile.js
Readfile.jsvar fs = require (' FS '); Fs.readfile (' file.txt ', ' utf-8 ', function (err, data) {if (err) {console.error (err);} else {console.log (data);}}); Console.log (' end. ');
"Code" Readfilesync.js
Readfilesync.jsvar fs = require (' FS '); var data = Fs.readfilesync (' file.txt ', ' utf-8 '); console.log (data); Console.log (' End. ');
In node. js, asynchronous I/O is implemented by a callback function.
"Code" Readfilecallback.js
Readfilecallback.jsfunction Readfilecallback (err, data) {if (err) {console.error (err);} else {console.log (data);}} var fs = require (' FS '); Fs.readfile (' file.txt ', ' utf-8 ', readfilecallback); Console.log (' End. ');
The work done by the Fs.readfile call only sends an asynchronous I/O request to the operating system, and then immediately returns and executes the following statement, which enters the event loop listener event after execution. When FS receives an event that the I/O request completes, the event loop actively invokes the callback function to complete the subsequent work.
3.2 Event node. js all asynchronous I/O operations are sent an event to the event queue upon completion. In the developer's opinion, the event is provided by the Eventemitter object. The callback functions of Fs.readfile and Http.createserver mentioned earlier are implemented by Eventemitter.
"Code" Event.js
Event.jsvar Eventemitter = require (' Events '). Eventemitter;var event = new Eventemitter ();//Registers a listener for event some_event Event.on (' some_event ', function () {Console.log ( ' some_event occured. '); SetTimeout (function () {//Send event Some_eventevent.emit (' Some_event ');}, 1000);
When does node. js go into the event loop? The answer is that the node. JS program starts with the event loop, ends with the event loop, and all the logic is the callback function of the event, so node. js is always in the event loop, and the program entry is the callback function for the first event in the event loop.
"Diagram" event loop
The 3.3 module and the package module are the basic components of the node. JS application, and the files and modules correspond to one by one. In other words, a node. js file is a module that may be JavaScript code, JSON, or compiled C/s extensions.
In the previous example, we used the Varhttp=require (' http '), where HTTP is a core module of node. JS, which is internally implemented in C + + and is encapsulated externally with JavaScript. We get the module through the Require function before we can use the object.
node. JS provides exports and require two objects, where exports is the interface that the module exposes, and require is used to obtain an interface from the outside of a module, the exports object of the acquired module.
3.3.1 A single load require does not load the module repeatedly, that is, the modules obtained are the same regardless of how many times require are called.
"Code" Loadmodule.js
var hello1 = require ('./module '); Hello1.setname (' Ichenxiaodoa '); Hello1.sayhello (); var Hello2 = require ('./module '); Hello2.setname (' Ichenxiaodao2 '); Hello1.sayhello (); Hello2.sayhello ();/** * because Hello1 and Hello2 point to the same instance, * So hello2.setname cover Hello1.setname, * final output Hello Ichenxiaodao2 */
3.3.2 Cover exports Sometimes we just want to encapsulate an object in the module.
"Code" Singleobject.js
function Hello () {var name;this.setname = function (thyname) {name = Thyname;}; This.sayhello = function () {console.log (' Hello ' + name);};}; Exports. hello = hello;
At this point we need to pass require ('./singleobject ') in other files. Hello to get the Hello object, which is slightly redundant and can be slightly simplified in the following ways:
"Code" Hello.js
function Hello () {var name;this.setname = function (thyname) {name = Thyname;}; This.sayhello = function () {console.log (' Hello ' + name);};}; Module.exports = Hello;
This allows you to get the object directly:
"Code" Gethello.js
var hello = require ('./hello '); var hello = new Hello (); Hello.sayhello (); Hello.setname (' Ichenxiaodao '); Hello.sayhello ( );
Note that the only change in the module interface is the use of Module.exports=hello instead of the Exports.hello=hello. When the module is referenced externally, its interface object is the Hello object itself to be exported, not the original exports.
In fact, exports itself is just an ordinary empty object, {}, which is specifically used to declare an interface, essentially through which it establishes a limited access interface to the inside of a module closure. Because it doesn't have any special place, it can be replaced with something else, such as the Hello object in our example above.
3.3.3 Creating a package is a deeper abstraction on a module basis, and node. JS's package is similar to a C/s library or java/. NET's class library. It encapsulates a separate feature for publishing, updating, dependency management, and versioning. node. JS implements the package mechanism based on 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 package description file Package.json. Packages that strictly conform to the COMMONJS specification should have the following characteristics:
? Package.json must be in the top-level directory of the package;
? Binary files should be in the bin directory;
? The JavaScript code should be in the Lib directory;
? The document should be in the doc directory;
? The unit test should be in the test directory.
node. JS's requirements for packages are not so stringent, as long as the top-level directory has Package.json and conforms to some specifications. Of course, in order to improve compatibility, we recommend that you strictly abide by the COMMONJS specification when making the package.
"Code" Somepackage/index.js
Exports.hello=function () {console.log (' hello ');}
"Code" Getpackage.js
Varsomepackage=require ('./somepackage '); Somepackage.hello ();
In the previous example, under the Somepackage folder, we created a file called Package.json, which reads as follows:
{"Main": "./lib/interface.js"}
Then rename the index.js to Interface.js and put it under the Lib subfolder. Call the package again in the same way, and it will still work.
When node. JS calls a package, it first checks the main field of the Package.json file in the package as the interface module for 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 the file that COMMONJS specifies to describe the package. See here for detailed settings.
3.3.4 node. JS Package Manager Local Installation: Npm[install/i][package_name]
Global installation: Npm[install/i]-g[package_name]
When we want to use a package as part of the project runtime, it is obtained through local mode and is installed using global mode if it is to be used at the command line.
to link a global package to a local:
Run in project directory: Npmlink[package_name]
link The local package to the global:
Running in the package directory: Npmlink
3.3.5 Release Package 1, through Npminit Interactive answer to produce a standard-compliant Package.json.
2, create a index.js as a package of excuses.
3, use Npmadduser according to prompt input user name, password, mailbox, wait for account creation completed.
4, after the completion can use the Npmwhoami test has already obtained the account.
5, in the Package.json directory run Npmpublish, wait a moment to complete the release.
If the package is updated later, simply modify the version field in the Package.json file and then re-use the Npmpublish command.
If you are not satisfied with the published package, you can use the Npmunpublish command to cancel the publication.
3.3.6 Commissioning
command-line debugging
Nodedebug[script.js]
Remote Debugging
Node--debug[=port]script.js
Node--debug-brk[=port]script.js
debugging node. js with Eclipse
Install plugin: chromedeveloper
Debugging with Node-inspector
1, installation Node-inspector:npminstall-gnode-inspector
2. Start Node-inspector
3. Startup script: Node--debug-brk=5858debug.js
4. Open the http://127.0.0.1:8080/debug?port=5858 in the browser
Node-inspector uses webkitwebinspector, so it can only be used in browsers such as Chrome, Safari and WebKit Kernels, not Firefox or InternetExplorer.
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/33130969
- Last modified: June 22, 2014 03:24