Node. js [4] introduction, installation and configuration, Quick Start

Source: Internet
Author: User

Prepared by BYVoid in Node. js Development Guide

Chapter 2 Introduction to Node. js

Node. js is a development platform that allows JavaScript to run on the server. It makes JavaScript a first-class citizen in the scripting language world, and is compatible with PHP, Python, Perl, and Ruby on the server.


Node. js can serve as a server to provide services to users. Compared with PHP, Python, and RubyonRails, it skips HTTP servers such as Apache and Nginx and directly targets frontend development.


Node. js can also call the C/C ++ code, so that you can make full use of the many existing function libraries, or use the C/C ++ to implement the part with high performance requirements.


Node. js adopts asynchronous I/O and event-driven architecture design. For high-concurrency solutions, the traditional architecture is a multi-threaded model that provides a system thread for each business logic, the time overhead of synchronous I/O calls is compensated by system thread switching. Node. js uses a single-threaded model. All I/O requests are asynchronous to avoid frequent context switching. Node. js maintains an event queue during execution. During execution, the program enters an event loop and waits for the next event to arrive. After each asynchronous I/O request is complete, it is pushed to the event queue, wait for the program process to process.

[Figure] Node. js Architecture



Chapter 4 install and configure Node. js
Build a Node. js Development Environment (Windows, Linux & Mac)
Node. js multi-version Manager


Chapter 2 Node. js Quick Start
$ Node-e "console. log ('helloworld ');"
HelloWorld
The statement to be executed can be directly executed as a node-e parameter.

REPL (Read-eval-printloop), that is, input-evaluate-output loop. Running a node without parameters starts a JavaScript interactive shell. If you execute a function, REPL will display the return value of the function below. If you enter an incorrect command, REPL immediately displays the error and outputs the call stack. At any time, press Ctrl + C twice in a row to launch the Node. js REPL mode.

[Figure] Node. js and PHP Architectures


Node. js parses the script file only when it is referenced to a part for the first time. In the future, it will directly access the memory to avoid repeated loading. Supervisor can help you implement this function. It will monitor your code changes and automatically restart Node. js. The usage is simple. First, use npm to install the supervisor:
$ Npminstall-gsupervisor
Run the supervisor command to start app. js:
$ Supervisorapp. js

[Figure] multithread synchronous I/O


[Figure] Single-thread asynchronous I/O


What is better for a Single-thread event-driven asynchronous I/O than the traditional multi-thread blocking I/O? In short, asynchronous I/O reduces the overhead of multithreading. For the operating system, it is very expensive to create a thread. You need to allocate memory to it and include it in scheduling. At the same time, you need to execute a memory swap during thread switching, the CPU cache is cleared. When switching back, you need to read information from the memory again, undermining 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 through callback functions.

[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.');
During the fs. readFile call, the job is to send an asynchronous I/O Request to the operating system, then immediately return and execute the following statement. After the execution, the event loop listening event is entered. When fs receives an event completed by an I/O Request, the event loop actively calls the callback function to complete subsequent work.

3.2 When all asynchronous I/O operations of event Node. js are completed, an event is sent to the event queue. In the developer's view, events are provided by the EventEmitter object. The callback functions of fs. readFile and http. createServer mentioned above are implemented through EventEmitter.

[Code] event. js
// Event. jsvar EventEmitter = require ('events '). eventEmitter; var event = new EventEmitter (); // registers a listener event of the event some_event. on ('some _ event', function () {console. log ('some _ event occured. ') ;}); setTimeout (function () {// send event some_eventevent.emit ('some _ event') ;}, 1000 );
When Will Node. js enter the event loop? The answer is Node. js programs start from the event loop and end to the event loop. All logic is the Event Callback Function, so Node. js is always in the event loop. The program entry is the callback function of the first event in the event loop.

Figure: Event Loop


The 3.3 Module and package module are the basic components of the Node. js application. The files and modules correspond one by one. In other words, a Node. js file is a module, which may be JavaScript code, JSON, or compiled C/C ++ extensions.

In the previous example, varhttp = require ('http') was used, where http is Node. A core module of js is implemented in C ++ internally and encapsulated in JavaScript externally. We can obtain this module through the require function before using the objects in the module.

Node. js provides two objects: exports and require. exports are public interfaces of the module, and require is used to obtain the interface of a module from the outside, that is, the exports object of the obtained module.

3.3.1 loading require at a time does not reload modules. That is to say, no matter how many requests are called, the obtained modules are the same.

[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, * therefore, hello2.setName overwrites hello1.setName and * finally outputs Hello ichenxiaodao2 */
3.3.2 overwrite exports. Sometimes we just want to encapsulate an object into a module.

[Code] singleobject. js
function Hello() {var name;this.setName = function(thyName) {name = thyName;};this.sayHello = function() {console.log('Hello ' + name);};};exports.Hello = Hello;
In this case, we need to get the Hello object through require ('./singleobject'). Hello in other files. This is slightly redundant and can be slightly simplified using the following method:
[Code] hello. js
function Hello() {var name;this.setName = function(thyName) {name = thyName;};this.sayHello = function() {console.log('Hello ' + name);};};module.exports = Hello;
In this way, you can directly obtain this object:
[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 that module. exports = Hello replaces exports. Hello = Hello. When this module is referenced externally, its interface object is the Hello object to be output, rather than the original exports.

In fact, exports itself is only a common null object, namely {}, which is used to declare an interface. In essence, it creates a limited access interface for the interior of the module closure. Because it does not have any special place, it can be replaced by other things, such as the Hello object in the above example.

3.3.3 creating a package is a further abstraction based on the module. The Node. js package is similar to a C/C ++ function library or a Java/. Net class library. It encapsulates an independent function for release, update, dependency management, and version control. Node. js implements the package mechanism according to CommonJS specifications, and develops npm to meet the package release and acquisition requirements.

The Node. js package is a directory containing a JSON package description file package. json. Packages that strictly comply with CommonJS specifications should have the following features:
The specified package. json file must be in the top-level directory of the package;
The binaries should be in the bin directory;
Pipeline JavaScript code should be in the lib directory;
The hosts file should be in the doc directory;
The testing unit test should be in the test directory.

Node. js does not have such strict requirements on packages, as long as the top-level directory contains package. json and complies with some specifications. To improve compatibility, we recommend that you strictly abide by the CommonJS specification when creating the package.

[Code] somepackage/index. js
exports.hello=function(){console.log('Hello');}

[Code] getpackage. js

varsomepackage=require('./somepackage');somepackage.hello();

In the somepackage folder in the preceding example, we create a file named package. json with the following content:

{"main":"./lib/interface.js"}

Rename index. js to interface. js and put it in the lib subfolder. You can still use this package again in the same way.


Node. when js calls a package, it first checks the package in the package. the main field of the json file, which is used as the interface module of the package. if the json or main field does not exist, the system will try to find the index. js or index. node is the package interface.

Package. json is the file specified by CommonJS to describe the package. For detailed settings, see here.

3.3.4 local installation of Node. js Package Manager: 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, we can get it in local mode. If we want to use it in command line, we will use global mode for installation.

Link the global package to the local device:
Run npmlink [package_name] in the project directory.

Link the local package to the global environment:
Run npmlink in the package directory

3.3.5 release package 1. A standard package. json is generated through the npminit interactive answer.
2. Create an index. js package as an excuse.
3. Use npmadduser to enter the user name, password, and email address as prompted, and wait until the Account creation is complete.
4. You can use npmwhoami to test whether your account has been obtained.
5. Run npmpublish in the directory where package. json is located. The release will be completed in a moment.

If the package is updated in the future, you only need to modify the version field in the package. json file, and then re-use the npmpublish command.

If you are not satisfied with the released package, you can use the npmunpublish command to cancel the release.

3.3.6 debugging Command Line Debugging
Nodedebug [script. js]

Remote debugging
Node -- debug [= port] script. js
Node -- debug-brk [= port] script. js

Use Eclipse to debug Node. js
Installation plug-in: ChromeDeveloper

Debug with node-inspector
1. Install node-inspector: npminstall-gnode-inspector
2. Start node-inspector
3. Startup Script: node -- debug-brk = 5858debug. js
4. Open http: // 127.0.0.1: 8080/debug in the browser? Port = 5858

Node-inspector uses WebKitWebInspector, so it can only be used in browsers with WebKit kernels such as Chrome and Safari, but does not support Firefox or InternetExplorer.


Document Information

  • Copyright statement: Free Reprint-non commercial-Non derivative-keep the signature | Creative Commons BY-NC-ND 3.0
  • Http://blog.csdn.net/cdztop/article/details/33130969
  • Last modification time: June 22, 2014

Related Article

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.