NODE. JS Development Guide Learning Notes

Source: Internet
Author: User
Tags emit

What is 1.node.js?
node. JS is a development platform that lets JS run on the server side, which can serve as a server to the user. In node. js
JavaScript is just a core JavaScript, or an implementation of ecmajavascript.
What can 2.node.js do?
JS is for the client, and node. JS is for the network. Use it to easily develop a lot of websites, social applications, services
device, and so on.
node. JS has a built-in HTTP server support that can implement a combination of Web sites and servers.
3. Asynchronous I/O and event-driven
The biggest feature of node. JS is the use of asynchronous I/O and event-driven architecture design. For all I/O, the requestor is async-
The system resources, deadlock, synchronization, low-speed connection attack, etc., which are caused by context switching. Nodejs maintains an event queue during execution, and the program enters the event loop at execution time waiting for the next event to be brought. After each asynchronous IO request is completed, it is pushed to the event queue for processing by the program process. The node. JS process handles only one event at a time, completing the
That is, enter the event loop to check and process the subsequent events. In this way, the CPU and memory will only handle one event at a time and allow time-consuming I/O operations to be executed in parallel.
The disadvantage is that it does not conform to the traditional developers to become thinking, often need to put a complete logical split into a single event, increase the Open
The difficulty of the hair and commissioning.
4.console.log () is equivalent to C's printf (), can also accept any parameter, support%d,%s variable reference
Eg:console.log ('%s:%d ', ' hello ', 25);
Hello:25
Undefined (This is the return value)
5. Input node Enter in the terminal can enter the REPL mode can be directly written to JS code to run
6. Different from the traditional server language (PHP for example)
Browser--http Server--php interpreter
node. js directly leaves the server open for browser users
Browser--node
7. Create an HTTP Server
App.js

var http = require (' http ');//Invoke HTTP Module

Http.createserver (function (req, res) {//Create server
Res.writehead ($, {' Content-type ': ' text/html '});
Res.write (' Res.end (' <p>hello world</p> ');
}). Listen (3000);//monitor 3000 port number

Console.log ("HTTP server is listening at Port 3000.");
Running node app.js at the terminal (note to find the current directory)
will find that noed is now waiting, and the process will not exit the event loop. cannot be implemented to refresh the page in real-time, it is not conducive to debugging, so you can install a module supervisor
Eg: $npm install-g supervisor
Exit Ctrl + C current stack, run supervisor App.js
When the code changes, the running script is stopped, then restarted, and the page is refreshed to see the data being refreshed in real time.
8. Blocking and threading
1. Synchronous I/O (blocking I/O)
threads typically take a long time to execute if they experience disk read-write or network traffic. At this point the OS will deprive the thread of CPU control and make it suspend execution. At the same time, the resources to other worker threads, this thread scheduling method is called blocking, when the I/O operation is complete, the OS will be the blocking state of the thread, reply to the CPU control, so that it continues to execute.
1. Asynchronous read File
var fs = require (' FS ');//Request FS Module
Fs.readfile (' file.txt ', ' utf-8 ', function (err,data) {//Read file
(The filename file format callback function (error, data in file) of the current directory/specified directory)
if (err) {
Console.log (err);
} else{
Console.log (data);
}
});
Console.log (' End '); The
can see that the end is printed first and then the Err or data is printed;
2. Synchronous read File
var fs = require (' FS ');
Fs.readfilesync (' file.txt ', ' utf-8 ', function (err,data) {//select synchronous mode to read the file
if (err) {
Console.log (err);
} else{
Console.log (data);
}
});
You can see that you print err or data before you print end

2. Asynchronous I/O (non-blocking I/O)
The blocking policy is not used for all I/O operations, and when a thread encounters an I/O operation, it simply sends the request to the OS and proceeds to the next statement, which, when the OS completes the I/O operation, notifies the thread performing the I/O operation as an event when the thread is handling the event at a particular time. As a result, node has an event loop mechanism that constantly checks for unhandled events and processes them sequentially.
3. Differences between the two:
In non-blocking mode, a thread is always performing a compute operation, and CPU utilization is 100%,I/O as an event notification.
In blocking mode, multithreading tends to improve system throughput because one thread is blocking other threads.
Specific:
Synchronous I/O asynchronous I/O
Increase throughput with multithreading to increase throughput single-threaded
Using multi-core CPU through event slice segmentation and thread scheduling to utilize multi-core through functional partitioning
Requires operating system scheduling multithreading using multicore CPUs can bind a single thread to a single core CPU
It is difficult to make full use of CPU resources to fully utilize CPU resources
Memory trajectory is large, data local weak memory trajectory is small, data locality is strong
Conforming to linear programming thinking does not conform to the traditional into thinking
4. You can run the JS code directly in the node environment
For example: node//Enter node environment
Console.log (' Never GIVE up ');//Print never GIVE up on the terminal
The second row of undefined is the return value
PS: Do not use alert, because alert is a method under window
or run the JS file
Like hello.js files.
Direct node Hello.js can execute

9.Node all asynchronous I/O operations will send an event to the event queue upon completion. The event is then triggered by a polling mechanism.
Event.js

var eventemitter = require (' Events '). eventemitter;//Request Event Object
var event = new Eventemitter (); Instantiating an Object

Event.on (' Some_event ', function () {//Register a listener for event some_event
Console.log (' some_event occured. ');
});

SetTimeout (function () {//1000MS sends events to the event object
Event.emit (' some_event ');
}, 1000);
2. Circular mechanism of events
The 1.node.js program is started by the event loop, to the end of the event loop. All logic is an event-based callback function
2. The callback function of the event can issue an I/O request or a direct trigger (emit) event during execution, and then return to the event loop after execution. The event loop checks that there are no unhandled events in the event queue, straight
Exits the event loop only if it is not detected, and the process ends.
10. Modules and packages are the most important pillars of node. It is not possible to develop a program of a certain size using only one file, usually by splitting, installing, and assembling the various functions, and the module confirms that it was born to achieve this. Packages and modules are inherently indistinguishable, except that packages are made up of multiple modules that provide a higher level of abstraction on a module basis.
Module.js
1. Loading the module
var name;
Exports.setname = function (thyname) {//expose SetName to the outside world
name = Thyname;
};
Exports.sayhello = function () {//SayHello exposed to the outside world
Console.log (' Hello ' + name);
};
Getmodule.js

var mymodule = require ('./module ');//request to load module.js this module

Mymodule.setname (' Andy '); Call Module.js inside the method
Mymodule.sayhello ();
Final output Hello Andy
2. One-time loading
var myModule1 = require ('./module ');
Mymodule.setname (' Andy ');

var myModule2 = require ('./module ');
Mymodule.setname (' King ');

Mymodule.sayhello ();//hello King
Because they point to the same instance, MyModule1 is covered by myModule2
3. Cover exports
function Hello () {
var name;

This.setname = function (thyname) {
name = Thyname;
};

This.sayhello = function () {
Console.log (' Hello ' + name);
};
};

Exports. Hello = hello;//before Hello is an exposed attribute to the outside world Hello is the function hello
In this way, you need require ('./filename ') to get the Hello object. Hello to get Hello object
! Trouble.
If the last line is such a reference module.exports = Hello, so long as var Hello = require ('./hello ');
OK.
Note: When referencing the module externally, its interface object is to output the Hello object itself, not the original expots.
Exports itself an ordinary empty object {}, specifically used to declare an interface, can be replaced with something else, such as Hello object. However, I can not assign values by exports direct copy instead of Module.exports, although they point to the same variable, but
The exports itself will be released after the module executes, and module will not, so it can only be changed by Module.exports.

11.node Debug Xxx.js can enter debug debug
Node--debug[=port] Script.js
Node--debug-brk[=port] Script.js can go to remote debugging the default port is 5858

NODE. JS Development Guide Learning 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.