First, the opening analysis
In the last chapter we have learned the basic theory of Nodejs knowledge, for these theoretical knowledge is essential to understand, in the subsequent chapters, we will be in control of the official document Step-by-step study of each part of the module, well, it is the protagonist of this article on the stage, the Global
Let's take a look at the official definition:
Global objects objects are available in all modules. Some of the objects aren ' t actually in the global scope but in the module Scope-this would be noted.
These objects are available in all modules. In fact, some objects are not in the global scope, but------these are identified in their module scopes.
In browsers, the top-level scope is the global scope. That means, browsers if you ' re in the global scope would var something
define a global variable.
In the Node this is different. The top-level scope is not the global scope; var something
Inside a Node module would be the local to that module.
The concept of global objects I think we should not be unfamiliar, in browsers, the highest level of scope is global scope, which means that if you use "var" in global scope to define a variable, this variable will be defined as global scope.
But in Nodejs, the highest level of scope is not global scope, and in a module, "VAR" is defined as a variable, which is only in the scope of this module.
In Nodejs, a variable defined in a module, a function or method is only available in that module, but it can be passed to the module outside by the use of the exports object.
However, in Node.js, there is still a global scope in which you can define variables, functions, or classes that are not required to be loaded through any of the modules.
At the same time, a number of global methods and global classes are defined as global namespaces in Nodejs, and any global variable, function, or object is a property value of that object.
In the REPL run environment, you can look at the details in the global object by following these statements, as shown in the following figure:
I'll say each of the following. The associated property value object that is mounted on the global object.
(1), Process
Process {Object} The Process object. The Process object section.
Process {Object} This is a progress object. In the following chapters I will elaborate, but here I would like to come up with an API to say.
Process.nexttick (callback)
On the next loop around the event loop call this callback. This isn't a simple alias to settimeout (FN, 0), it's much more efficient. It typically runs before any other I/O events fire, but there are some. Process.maxtickdepth below.
Call the callback callback function in the next loop of the event loop. This is not a simple alias for the settimeout (FN, 0) function because it is much more efficient.
This function can call our callback function prior to any I/O beforehand. This function is important to you if you want to do something before the I/O operation occurs after the object is created.
There are a lot of people who don't understand the usage of Process.nexttick in Node.js, so let's take a look at what Process.nexttick is and how to use it.
Node.js is single-threaded, except for system IO, which handles only one event at a time during its event polling process. You can think of event polling as a large queue, and at each point in time, the system will only handle one event.
Even if your computer has multiple CPU cores, you cannot handle multiple events concurrently. But it is this feature that makes node.js suitable for processing I/O applications, and not for that type of CPU operation.
In each I/O application, you only need to define a callback function for each input output, and they are automatically added to the event polling processing queue.
This callback function is triggered when the I/O operation is complete. The system will then continue to process other requests.
In this mode of processing, the meaning of Process.nexttick () is to define an action and let the action be executed at the point at which the next event polls. Let's take a look at an example. The example has an foo () that you want to call at the next point in time, and you can do this:
Copy Code code as follows:
function foo () {
Console.error (' foo ');
}
Process.nexttick (foo);
Console.error (' Bar ');
Running the above code, the information you print from the terminal below will see that "bar" output is in front of "foo". This verifies the above saying that Foo () is running at the next point in time.
Copy Code code as follows:
You can also use the settimeout () function to achieve seemingly the same effect:
Copy Code code as follows:
settimeout (foo, 0);
Console.log (' Bar ');
But in the internal processing mechanism, Process.nexttick () and settimeout (FN, 0) are different, Process.nexttick () is not a simple delay, he has more features.
More precisely, Process.nexttick ()-defined calls create a new child stack. In the current stack, you can perform any number of operations. But once Netxtick is invoked, the function must be returned to the parent stack. The event polling mechanism then waits for new events to be processed, and if a nexttick call is found, a new stack is created.
Let's take a look at what happens when using Process.nexttick ():
Cross CPU-intensive tasks across multiple events:
In the following example there is a compute (), and we want this function to execute as consistently as possible to perform some computational intensive tasks.
But at the same time, we want the system not to be blocked by this function, but also need to be able to respond to handling other events. This application pattern is like a single-threaded Web service server. Here we can use Process.nexttick () to cross execute compute () and normal event response.
Copy Code code as follows:
var http = require (' http ');
function Compute () {
Performs complicated calculations continuously
// ...
Process.nexttick (COMPUTE);
}
Http.createserver (function (req, res) {
Res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Hello world ');
}). Listen (5000, ' 127.0.0.1 ');
Compute ();
In this mode, we do not need a recursive call to compute (), we only need to use the Process.nexttick () definition compute () in the event loop to execute at the next point in time.
In this process, if a new HTTP request comes in, the event loop mechanism processes the new request first and then calls Compute ().
Conversely, if you put compute () in a recursive call, the system will always block in compute (), unable to process the new HTTP request. You can try it on your own.
Of course, we can't use Process.nexttick () to get the real benefits of parallel execution on multiple CPUs, which only simulates the same application being staged on the CPU.
(2), Console
console {Object} Used to print to stdout and stderr. The stdio section.
The console {object} is used to print to standard output and error output. Look at the following tests:
Copy Code code as follows:
Console.log ("Hello bigbear!");
for (var i in console) {
Console.log (i+ "" +console[i]);
}
The following output results are obtained:
Copy Code code as follows:
var log = function () {
Process.stdout.write (format.apply (this, arguments) + ' \ n ');
}
var info = function () {
Process.stdout.write (format.apply (this, arguments) + ' \ n ');
}
var warn = function () {
Writeerror (format.apply (this, arguments) + ' \ n ');
}
var error = function () {
Writeerror (format.apply (this, arguments) + ' \ n ');
}
var dir = function (object) {
var util = require (' util ');
Process.stdout.write (Util.inspect (object) + ' \ n ');
}
var time = function (label) {
Times[label] = Date.now ();
}
var timeend = function (label) {
var duration = Date.now ()-Times[label];
Exports.log (' Undefined:nanms ', label, duration);
}
var trace = function (label) {
TODO probably can to does this better with V8 ' s debug object once the IS
Exposed.
var err = new Error;
Err.name = ' Trace ';
err.message = Label | | '';
Error.capturestacktrace (err, Arguments.callee);
Console.error (Err.stack);
}
var assert = function (expression) {
if (!expression) {
var arr = Array.prototype.slice.call (arguments, 1);
Require (' assert '). Ok (False, format.apply (this, arr));
}
}
With these functions, we basically know what Nodejs is adding to the global scope, but the relevant APIs on the console object are only more advanced encapsulation of the "stdout.write" on the process object to the global object.
(3), exports and Module.exports
In Nodejs, there are two scopes, divided into global scope and module scope.
Copy Code code as follows:
var name = ' Var-name ';
name = ' name ';
Global.name= ' Global-name ';
this.name = ' module-name ';
Console.log (Global.name);
Console.log (this.name);
Console.log (name);
We see var name = ' Var-name '; name = ' name '; is defined as a local variable;
and Global.name= ' Global-name '; is to define a name property for the global object,
and this.name = ' module-name '; is a Name property defined for the module object
So let's verify that the following is saved as Test2.js and run
Copy Code code as follows:
var T1 = require ('./test1 ');
Console.log (T1.name);
Console.log (Global.name);
As can be seen from the results, we successfully imported the Test1 module and ran the Test1 code because global.name was exported in Test2,
The t1.name is defined by the THIS.name in the Test1 module, stating that this points to a module scope object.
A little difference between exports and module.exports
Module.exports
Is the real interface, and exports is just one of its AIDS tools. The final return to the call is Module.exports
not exports.
All the properties and methods collected by the exports are assigned a value Module.exports
. Of course, there is a premise thatModule.exports
本身不具备任何属性和方法
。
如果,
Module.exports
已经具备一些属性和方法,那么exports收集来的信息将被忽略。
Give me a chestnut:
Create a new file Bb.js
Copy Code code as follows:
Exports.name = function () {
Console.log (' My name is Big Bear! ') ;
} ;
Create a test file Test.js
Copy Code code as follows:
var bb= require ('./bb.js ');
Bb.name (); ' My name is Big Bear! '
Modify Bb.js as follows:
Copy Code code as follows:
Module.exports = ' bigbear! ';
Exports.name = function () {
Console.log (' My name is Big Bear! ') ;
} ;
Referencing the execution bb.js again
Copy Code code as follows:
var bb= require ('./bb.js ');
Bb.name (); Has no method ' name '
As it is, your module does not necessarily have to return "instantiated objects". Your module can be any legitimate JavaScript object--boolean, number, date, JSON, string, function, array, and so on.
(4), settimeout,setinterval,process.nexttick,setimmediate
The following is a summary form
Nodejs is characterized by event-driven, asynchronous I/O generated high concurrency, the engine is the event loop, the event is categorized into the corresponding event observer, such as idle observer, timer Observer, I/O observer, etc., the event loop each loop called tick, Each tick the event from the Event Viewer in the order in which it is processed.
The timer created when calling settimeout () or setinterval () is placed in a red-black tree within the timer Viewer, and the corresponding callback function is executed immediately when a tick is checked from the red-black tree to see if the timer exceeds the timed time. SetTimeout () and setinterval () are used as timers, and their difference is that the latter is a repetitive trigger, and because the time is too short it will cause the processing of the previous trigger to be triggered immediately after the first time.
Since the timer is a timeout trigger, this can lead to lower trigger accuracy, such as the timeout set by settimeout is 5 seconds, when the event loop in the 4th second to a task, its execution time 3 seconds, then settimeout callback function will expire 2 seconds to execute, This is the cause of the reduction in precision. And because the use of red-black tree and iterative way to save timer and judge Trigger, more wasteful performance.
All the callback functions that are set by using Process.nexttick () are placed in the array and are executed immediately at the next tick, which is lighter and has high time precision.
The callback function set by Setimmediate () is also called at the next tick, and Process.nexttick () differs in two points:
1, the observer to which they belong is executed in a different priority, Process.nexttick () belongs to the Idle Observer, Setimmediate () belongs to the Check Observer, idle priority >check.
The callback function set by 2,setimmediate () is placed in a linked list, and each tick executes only one callback in the list. This is to ensure that each tick can be executed quickly.
Second, to sum up
1, understand the meaning of global object existence
A little difference between 2,exports and module.exports
What is built at the bottom of the 3,console (the high-level encapsulation of the process object)
The difference between the 4,settimeout,setinterval,process.nexttick,setimmediate
Two scopes in the 5,nodejs