Nodejs Learning Notes-global objects and global variables

Source: Internet
Author: User

Global objects

In Browser javascript, window is the global object, and Node. JS is global, and all global variables (except the global Itself) are properties of the global Object.


In Node. js, we can directly access the properties of global without having to include it in the app.


Global variables

The fundamental role of global is to be the host of Variables. As defined by ECMAScript, variables that meet the following conditions are global variables:

1, in the outermost definition of the variable;

2, the properties of the global object;

3. implicitly-defined variables (variables that are not directly assigned) are Undefined.


When defining a global variable, This variable is also a property of the global object, and Vice Versa. It is important to note that it is not possible to define variables at the outermost layer in Node. JS because all user code belongs to the current module, and the module itself is not the outermost context.

Note: always use var to define variables to avoid introducing global variables, because global variables pollute namespaces and increase the risk of code COUPLING.



__filename

The double underscore filename represents the file name of the currently executing script, which will output the absolute path where the file is Located. It is not necessarily the same as the file name specified by the command-line arguments. If the value returned in the module is the path to the module File.


Example: Create a main.js with the following code:

Output global variable __filename value Console.log (__filename);


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/8A/0F/wKiom1glNznjtYPGAAAeFtDQr-A661.png "title=" Qq20161111111219.png "alt=" wkiom1glnznjtypgaaaeftdqr-a661.png "/>


__dirname

Double underline dirname represents the directory where the current execution script resides


Create a main.js with the following code:

Output global variable __dirname value Console.log (__dirname);


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M01/8A/0B/wKioL1glOS_zWR-DAAAPUKL8TsY907.png "title=" Qq20161111112059.png "alt=" wkiol1glos_zwr-daaapukl8tsy907.png "/>


SetTimeout (cb,ms)

setTimeout (cb,ms) global function executes the specified function (cb) after the specified number of milliseconds (ms)

SetTimeout () executes a specified function only once, returning a handle value representing the timer


Create the following code in Main.js:

function Printhello () {console.log (' Hello world! ');} After 2 seconds, execute the Printhello function settimeout (printhello, 2000);


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s4.51cto.com/wyfs02/M00/8A/0F/wKiom1glO7KiXme4AAAPvXhBHN0336.png "title=" Qq20161111113150.png "alt=" wkiom1glo7kixme4aaapvxhbhn0336.png "/>


Cleartimeout (t)

Cleartimeout (t) global function to stop a timer that was previously created by setTimeout ()

The parameter T is a timer created by the setTimeout () function


Create the following code in Main.js:

function Printhello () {console.log (' Hello world! ');} After 2 seconds, execute the Printhello function var t = setTimeout (printhello, 2000);//clear timer cleartimeout (t);


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M02/8A/0F/wKiom1glPQugaTtTAAAQhIYBEcQ758.png "title=" Qq20161111113735.png "alt=" wkiom1glpqugatttaaaqhiybecq758.png "/>


SetInterval (cb,ms)

setinterval (cb,ms) global function executes the specified function (cb) after the specified number of milliseconds (ms)

Returns a handle value representing the Timer. You can use the Clearinterval (t) function to clear the timer

The SetInterval () method keeps calling functions until Clearinterval () is called or the window is closed


Create the following code in Main.js:

function Printhello () {console.log (' Hello world! ');} After 2 seconds, execute the Printhello function setinterval (printhello, 2000);


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M00/8A/0C/wKioL1glP6rhv3r5AAAR--dli7Q655.png "title=" Qq20161111114741.png "alt=" wkiol1glp6rhv3r5aaar--dli7q655.png "/>


Console

Console is used to provide console standard output, which is a debugging tool provided by the JScript engine of Internet explorer, and later becomes a de facto standard for browsers. Node. JS uses this standard to provide a console object that is consistent with customary behavior to output characters to the standard output stream (stdout) or standard error stream (stderr).


The following are the methods of the console Object:

Serial number Method & Description
1

Console.log ([data][, ...])

Prints characters to the standard output stream and ends with a newline character. The method receives several parameters and, if there is only one argument, outputs the string form of the Parameter. If there are multiple parameters, it is output in a format similar to the C-language printf () command.

2

Console.info ([data][, ...])

P The function of this command is to return an informational message, which is not very different from console.log, except that only the text will be printed in chrome, and the rest will display a blue exclamation point.

3

Console.error ([data][, ...])

The output error Message. The console displays a red fork when an error occurs.

4

Console.warn ([data][, ...])

The output warning Message. The console appears with a yellow exclamation point.

5

Console.dir (obj[, Options])

Used to examine an object (inspect) and display it in a format that is easy to read and Print.

6

Console.time (label)

The output time, which indicates that the timing starts.

7

Console.timeend (label)

End time, indicating that the timing is over.

8

Console.trace (message[, ...])

The current execution of the code in the stack of call path, This test function is very helpful, as long as you want to test the function inside the console.trace to join the LINE.

9

Console.assert (value[, message][, ...])

Used to determine if an expression or variable is true, takes two arguments, the first argument is an expression, and the second parameter is a string. The second parameter is output only if the first argument is false, otherwise there will be no Result.


Console.log (): prints characters to the standard output stream and ends with line breaks.

Console.log accepts several parameters, and if there is only one argument, it outputs the string form of the Parameter. If there are multiple parameters, it is output in a format similar to the C-language printf () command.

The first argument is a string, and if there are no arguments, only one line break is Printed.

650) this.width=650; "src=" http://s5.51cto.com/wyfs02/M01/8A/0C/wKioL1glUxLwNFbGAAALaBJBMlI402.png "title=" Qq20161111131008.png "alt=" wkiol1gluxlwnfbgaaalabjbmli402.png "/>


Console.error (): Same as Console.log () usage, just output to standard error stream

Console.trace (): outputs the current output to the standard error stream


Create a main.js with the following code:

Console.info (' program starts executing: '), var counter =10;console.log (' count:% ', counter); console.time (' get data ');////execute some code// Console.timeend (' Get Data '); console.info (' program execution completed ');


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/8A/0C/wKioL1glVbHSo1k4AAALMm2DO-Q474.png "title=" Qq20161111132246.png "alt=" wkiol1glvbhso1k4aaalmm2do-q474.png "/>


Process

Process process is a global variable, which is a property of the global Object.

It is used to describe the object of the current Node. JS process state and provides a simple interface to the operating System. Usually when you write a local command-line program, you have to deal with it.


Some of the most common member methods of the Process object are described below.

Serial number Events & Descriptions
1

Exit

Triggered when the process is ready to exit.

2

Beforeexit

This event is triggered when node clears the event loop and there is no other Arrangement. In general, node exits when no process is scheduled, but the ' beforeexit ' listener can be called asynchronously so that node continues Execution.

3

Uncaughtexception

This event is triggered when an exception bubbles back into the event loop. If you add a monitor to an exception, the default action (print stack trace information and Exit) does not occur.

4

Signal Events

Triggered when the process receives a signal. The list of signals is described in the standard POSIX signal names, such as SIGINT, SIGUSR1, etc.


Create a main.js with the following code:

Process.on (' exit ', function (code) {//) The following code will never execute setTimeout (function () {console.log (' The code will not execute ');    },0); Console.log (' exit Code: ', code);}); Console.log (' End of program execution ');


Execute the main.js file on the command line as Follows:

650) this.width=650; "src=" http://s4.51cto.com/wyfs02/M01/8A/10/wKiom1glW7SzroRkAAAHUziJzfA572.png "title=" Qq20161111134823.png "alt=" wkiom1glw7szrorkaaahuzijzfa572.png "/>


For more information about the process, refer to the Beginner's tutorial

Http://www.runoob.com/nodejs/nodejs-global-object.html


This article is from the "dapengtalk" blog, make sure to keep this source http://dapengtalk.blog.51cto.com/11549574/1871761

Nodejs Learning Notes-global objects and global variables

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.