Big Bear Nodejs's------global Objects Universal Object

Source: Internet
Author: User

First, the opening analysis

In the last chapter, we learned the basic theoretical knowledge of nodejs, for these theoretical knowledge is very important to understand, in the following chapters, we will gradually learn from the official documents inside the various parts of the module, well, this is the time for the protagonist to debut,Global

Let's take a look at the official definition:

Globals Objects Global Objects These objects is available in all modules. Some of these objects aren ' t actually in the global scope but 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 they------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 Node this is different. The top-level scope is not the global scope; var somethinginside a Node module would be the local to that module.

The concept of global objects I think we should not feel strange, in the browser, 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 the Nodejs is not the same, the highest level of scope is not a global scope, in a module with "var" defined variables, this variable is only within the Scope of this module.

In Nodejs, a variable defined in a module, a function or method is available only in that module, but can be passed to the outside of the module by using the exports object.

However, in node. js, there is still a global scope where you can define variables, functions, or classes that do not need to be loaded by any module.

At the same time, some global methods and global objects are predefined 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 observe the details of the global object in the following statement, see:

I'll talk about the related property value objects that are mounted on the Global object.

(1),Process

Process {Object} The process Object. See the Process Object section.

Process {Object} This is a processing object. I'll elaborate on the following chapters, but here I'm going to take out an API for a moment.

   Process.nexttick (callback)

On the next loop around the event loop, 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 is some exceptions. See 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.

The function can call our callback function before any I/O is preceded. This function is important to you if you want to perform certain operations before an I/O operation occurs after an 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, where only one event is processed at the same time during its event polling. You can think of event polling as a large queue, and at every point in time, the system will only handle one event.

Even if your computer has multiple CPU cores, you can't handle multiple events in parallel at the same time. But it is this feature that makes node. js suitable for I/O-type applications, not for CPU-based applications.

In each I/O type application, you only need to define a callback function for each input and output, and they will automatically be 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 processing mode, Process.nexttick () means defining an action and letting the action be executed at the point in time at which the next event is polled. Let's look at an example. In the example there is a foo (), you want to call him at the next point in time, you can do this:

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 the "bar" output is in front of "foo". This verifies that Foo () is running at the next point in time.

You can also use the settimeout () function to achieve seemingly the same effect:

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 mere delay, he has more characteristics.

More precisely, Process.nexttick () defines a call that creates a new child stack. In the current stack, you can perform any number of actions. But once Netxtick is called, the function must return to the parent stack. The event polling mechanism then waits for new events to be processed, and if a call to Nexttick is found, a new stack is created.

Let's take a look at, under what circumstances use Process.nexttick ():

cross-perform CPU-intensive tasks across multiple events:

In the following example there is a compute (), and we want this function to perform as consistently as possible for some computationally intensive tasks.

But at the same time, we want the system not to be blocked by this function, but also to be able to respond to other events. This application pattern is like a single-threaded Web service server. Here we can use Process.nexttick () to cross-perform compute () and normal event responses.

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 don't need a recursive call to compute (), we just need to use 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 before calling compute ().

Conversely, if you put compute () in a recursive call, the system will always block in compute () and cannot process new HTTP requests. You can try it yourself.

Of course, we can't get the real benefit of parallel execution on multiple CPUs with Process.nexttick (), which just simulates the same application being staged on the CPU.

(2),Console

  Console {Object} used to print to stdout and stderr. See the Stdio section.

  The console {object} is used for printing to standard output and error output. See the following tests:

  

1 console.log ("Hello bigbear!") ) ; 2  for (var in console) {3     console.log (i+ "  " +console[i]); 4 }

The following output results are obtained:

  

1 varLog =function () {2Process.stdout.write (Format.apply ( This, arguments) + ' \ n ');3 }4 varinfo =function () {5Process.stdout.write (Format.apply ( This, arguments) + ' \ n ');6 }7 varWarn =function () {8Writeerror (Format.apply ( This, arguments) + ' \ n ');9 }Ten varError =function () { OneWriteerror (Format.apply ( This, arguments) + ' \ n '); A } - varDIR =function(object) { -   varUtil = require (' util ')); theProcess.stdout.write (Util.inspect (object) + ' \ n '); - } - varTime =function(label) { -Times[label] =Date.now (); + } - varTimeend =function(label) { +   varDuration = Date.now ()-Times[label]; AExports.log (' Undefined:nanms ', label, duration); at } - vartrace =function(label) { -   //TODO probably can-do-better with V8 's debug object once that's -   //exposed. -   varErr =NewError; -Err.name = ' Trace '; inerr.message = Label | | ‘‘; - error.capturestacktrace (err, Arguments.callee); to Console.error (err.stack); + } - varassert =function(expression) { the   if(!expression) { *     vararr = Array.prototype.slice.call (arguments, 1); $Require (' assert '). OK (false, Format.apply ( This, arr));Panax Notoginseng   } -}

  With these functions, we basically know what Nodejs is adding to the global scope, but the related API on the console object is just a more advanced encapsulation of the "stdout.write" on the process object hanging on to the global object.

(3),exports and Module.exports

In Nodejs, there are two scopes, divided into global scope and module scope

var name = ' Var-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 a defined local variable;

and Global.name= ' Global-name '; is to define a name property for the global object,

and this.name = ' module-name '; is to define a Name property for the module object

So let's verify, save the following as Test2.js, run

  

var t1 = require ('./test1 ');  Console.log (t1.name);  Console.log (global.name);  

As we can see from the results, we successfully imported the Test1 module and ran the Test1 code because global.name was output in Test2,

The t1.name is defined by THIS.name in the Test1 module, which indicates that this is a module-scoped object.

  A little difference between exports and module.exports

    Module.exportsIs the real interface, exports is just one of its auxiliary tools. The final return to the call is Module.exports instead of exports.

All the properties and methods collected by the exports are assigned Module.exports . Of course, there is a premise thatModule.exports本身不具备任何属性和方法

    如果,Module.exports已经具备一些属性和方法,那么exports收集来的信息将被忽略。

  Give me a chestnut:

Create a new file Bb.js

function () {    console.log (' My name is Big Bear! ');} ;

Create a test file Test.js

  

var bb= require ('./bb.js '//  ' My name is Big Bear! '

Modify the Bb.js as follows:

Module.exports = ' bigbear! '  function() {    console.log (' My name is Big Bear! ');} ;

Re-referencing execution bb.js

var bb= require ('./bb.js '// has no method ' name '

  Your module does not necessarily have to return "instanced 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 are summarized in the form of

    Nodejs is characterized by event-driven, asynchronous I/O generation of high concurrency, the engine that produces this feature is the event loop, events are categorized into the corresponding event observers, such as idle observer, timer Observer, I/O observer, and so on, each cycle of the event loop is called Tick, Each tick is processed by taking an event from the event watcher in a sequential order.

The timer created when calling settimeout () or setinterval () is placed in a red-black tree inside the timer viewer, and each tick is checked from the red-black tree to see if the timer exceeds the timed time, and executes the corresponding callback function immediately. SetTimeout () and setinterval () are used when timers, their difference is that the latter is repeated triggering, and because the time set too short will cause the previous trigger after the processing has just completed immediately after the trigger.

Since the timer is a time-out trigger, which results in lower trigger accuracy, such as a timeout of 5 seconds set with SetTimeout, when the event loop follows a task in the 4th second and its execution time is 3 seconds, then SetTimeout's callback function expires 2 seconds, This is why the accuracy is reduced. And because the use of red-black tree and iterative way to save timers and judgment trigger, more wasteful performance.

All of the callback functions set with Process.nexttick () are placed in the array and are executed immediately at the next tick, which is lightweight and time-accurate.

The callback function set by Setimmediate () is also called at the next tick, and the difference between Process.nexttick () is two points:

1, the observers they belong to are executed in a different priority, Process.nexttick () belongs to the Idle Observer, Setimmediate () belongs to the Check Observer, idle priority >check.

2,setimmediate () sets the callback function to be placed in a linked list each time the tick executes only one callback in the linked list. This is to ensure that each tick can be executed quickly.

Two, summarize

  1, understanding the meaning of global object existence

2,a little difference between exports and Module.exports

3,What is the bottom of the console built (high-level encapsulation of the process object)

4,the difference between settimeout,setinterval,process.nexttick,setimmediate

Two scopes in 5,nodejs

hahaha, the end of this article, not to be continued, hope and we have enough communication, common progress ... To shout ... (*^__^*)          

Big Bear Nodejs's------global Objects Universal Object

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.