Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Global Objects

Node.js Global Objects

In JavaScript there is a special object called the Global Object; it and all its properties can be accessed anywhere in the program, namely global variables.

In browser JavaScript, window is usually the global object, while in Node.js the global object is global; all global variables (except global itself) are properties of the global object.

In Node.js we can directly access the properties of global without including it in the application.


Global Objects and Global Variables

The most fundamental role of global is to host global variables. According to the ECMAScript definition, a variable that meets the following conditions is a global variable:

When you define a global variable, it also becomes a property of the global object, and vice versa. It should be noted that in Node.js you cannot define a variable at the outermost level, because all user code belongs to the current module, and the module itself is not the outermost context.

Note: It is best not to use var to define variables so as to avoid introducing global variables, because global variables pollute the namespace and increase the risk of code coupling.


__filename

** __filename** represents the filename of the script currently being executed. It outputs the absolute path of the file's location and is not necessarily the same as the filename specified by the command-line argument. If in a module, the returned value is the path of the module file.

Example

Create the file main.js with the following code:



// Output the value of the global variable __filename

console.log( __filename );

Execute the main.js file with the following code:



$ node main.js

/web/com/runoob/nodejs/main.js


__dirname

__dirname Represents the directory where the currently executing script resides.

Example

Create the file main.js with the following code:



// Output the value of the global variable __dirname

console.log( __dirname );

Execute the main.js file with the following code:



$ node main.js

/web/com/runoob/nodejs


setTimeout(cb, ms)

setTimeout(cb, ms) The global function executes the specified function (cb) after the specified number of milliseconds (ms).: setTimeout() executes the specified function only once.

Returns a handle value representing the timer.

Example

Create the file main.js with the following code:



function printHello(){

   console.log( "Hello, World!");

}

// execute the above function after two seconds

setTimeout(printHello, 2000);

Execute the main.js file with the following code:



$ node main.js

Hello, World!


clearTimeout(t)

clearTimeout( t ) The global function is used to stop a timer previously created by setTimeout(). Parameter t is the timer created by the setTimeout() function.

Example

Create the file main.js with the following code:



function printHello(){

   console.log( "Hello, World!");

}

// execute the above function after two seconds

var t = setTimeout(printHello, 2000);



// Clear timer

clearTimeout(t);

Execute the main.js file with the following code:



$ node main.js


setInterval(cb, ms)

setInterval(cb, ms) The 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 the function until clearInterval() is called or the window is closed.

Example

Create the file main.js with the following code:



function printHello(){

   console.log( "Hello, World!");

}

// execute the above function after two seconds

setInterval(printHello, 2000);

Execute the main.js file with the following code:



$ node main.js

Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! ……

The above program outputs "Hello, World!" every two seconds and will keep running forever until you press ctrl + c button in the upper right of the page.


console

console is used to provide standard console output; it was a debugging tool provided by Internet Explorer's JScript engine and later gradually became a de facto standard in browsers.

Node.js follows this standard, providing a console object consistent with customary behavior, used to output characters to the standard output stream (stdout) or standard error stream (stderr).

console methods

The following are the methods of the console object:

No. Method & Description
1 console.log([data][, ...])
Prints characters to the standard output stream and ends with a newline. This method accepts several parameters; if there is only one parameter, it outputs the string form of that parameter. If there are multiple parameters, it outputs them in a format similar to the C language printf() command.
2 console.info([data][, ...])
This command is used to return informational messages; it is not very different from console.log, except that in Chrome it only outputs text, while others display a blue exclamation mark.
3 console.error([data][, ...])
Outputs error messages. The console displays a red cross when an error occurs.
4 console.warn([data][, ...])
Outputs warning messages. The console displays a yellow exclamation mark.
5 console.dir(obj[, options])
Used to inspect an object and display it in an easy-to-read and printable format.
6 console.time(label)
Outputs the time, indicating the start of timing.
7 console.timeEnd(label)
Outputs the end time, indicating the end of timing.
8 console.trace(message[, ...])
The call path of the currently executing code in the stack; this is helpful for testing function execution, just add console.trace inside the function you want to test.
9 console.assert(value[, message][, ...])
Used to determine whether an expression or variable is true; it accepts two parameters, the first is the expression and the second is a string. Only when the first parameter is false will the second parameter be output; otherwise there will be no result.

console.log(): Prints characters to the standard output stream and ends with a newline.

console.log accepts several parameters; if there is only one parameter, it outputs the string form of that parameter. If there are multiple parameters, it outputs them in a format similar to the C language printf() command.

The first parameter is a string; if there are no parameters, only a newline is printed.



console.log('Hello world'); 

console.log('byvoid%diovyb'); 

console.log('byvoid%diovyb', 1991); 

The running result is:



Hello world 

byvoid%diovyb 

byvoid1991iovyb 



console.trace();

The running result is:



Trace: 

at Object. (/home/byvoid/consoletrace.js:1:71) 

at Module._compile (module.js:441:26) 

at Object..js (module.js:459:10) 

at Module.load (module.js:348:31) 

at Function._load (module.js:308:12) 

at Array.0 (module.js:479:10) 

at EventEmitter._tickCallback (node.js:192:40)

Example

Create the file main.js with the following code:



console.info("程序开始执行:");



var counter = 10;

console.log("计数: %d", counter);



console.time("获取数据");

//

// Execute some code

// 

console.timeEnd('获取数据');



console.info("程序执行完毕。")

Execute the main.js file with the following code:



$ node main.js

Program execution starts:

计数: 10

获取数据: 0ms

程序执行完毕


process

process is a global variable, that is, a property of the global object.

It is an object that describes the state of the current Node.js process and provides a simple interface with the operating system. Usually, when you write local command-line programs, you can't avoid dealing with it. Below we will introduce some of the most commonly used member methods of the process object.

No. Event & Description
1 exit
Triggered when the process is about to exit.
2 beforeExit
This event is triggered when node has cleared the event loop and has no other pending work. Generally, node exits when there is no pending work, but listeners for 'beforeExit' can make asynchronous calls, so node will continue executing.
3 uncaughtException
Triggered when an exception bubbles back to the event loop. If a listener is added for the exception, the default action (printing the stack trace and exiting) will not occur.
4 Signal Events
Triggered when the process receives a signal. For the list of signals, see the standard POSIX signal names, such as SIGINT, SIGUSR1, etc.

Example

Create the file main.js with the following code:



process.on('exit', function(code) {



  // This code will never execute

  setTimeout(function() {

    console.log("该代码不会执行");

  }, 0);

  

  console.log('退出码为:', code);

});

console.log("程序执行结束");

Execute the main.js file with the following code:



$ node main.js

程序执行结束

退出码为: 0

Exit status code

The exit status codes are as follows:

Status code Name & Description
1 Uncaught Fatal Exception
An uncaught exception occurred and was not handled by a domain or an uncaughtException handler.
2 Unused
Reserved, reserved by Bash for built-in misuse
3 Internal JavaScript Parse Error
A parsing error is caused when JavaScript source starts the Node process. Very rare, only occurs when developing Node.
4 Internal JavaScript Evaluation Failure
JavaScript source starts the Node process and fails to return a function during evaluation. Very rare, only occurs when developing Node.
5 Fatal Error
A fatal, unrecoverable error in V8. It is usually printed to stderr with the content: FATAL ERROR
6 Non-function Internal Exception Handler
An uncaught exception where the internal exception handler was somehow set to a non-function and cannot be called.
7 Internal Exception Handler Run-Time Failure
An uncaught exception, and the exception handler itself threw an exception while handling it. For example, if process.on('uncaughtException') or domain.on('error') threw an exception.
8 Unused
Reserved; in previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception.
9 Invalid Argument
An unknown argument may have been given, or an argument was given without a value.
10 Internal JavaScript Run-Time Failure
JavaScript source throws an error when starting the Node process; very rare, only occurs when developing Node.
12 Invalid Debug Argument
The --debug and/or --debug-brk parameters were set, but the wrong port was selected.
128 Signal Exits
If Node receives a fatal signal, such as SIGKILL or SIGHUP, the exit code will be 128 plus the signal code. This is standard Unix practice, with the exit signal code placed in the high bits.

Process Properties

Process provides many useful properties to help us better control system interaction:

No. Attribute & Description
1 stdout
Standard output stream.
2 stderr
Standard error stream.
3 stdin
Standard input stream.
4 argv
The argv property returns an array consisting of the various arguments when the script is executed from the command line. Its first member is always node, the second is the script filename, and the remaining members are the script's arguments.
5 execPath
Returns the absolute path of the Node binary executing the current script.
6 execArgv
Returns an array whose members are the command-line arguments between the Node executable and the script file when the script is executed from the command line.
7 env
Returns an object whose members are the current shell's environment variables
8 exitCode
The code when the process exits; if the process exits via process.exit(), there is no need to specify an exit code.
9 version
The version of Node, such as v0.10.18.
10 versions
A property containing the version and dependencies of node.
11 config
An object containing the JavaScript configuration options used to compile the current node executable. It is the same as the "config.gypi" file generated by running the ./configure script.
12 pid
The process ID of the current process.
13 title
The process name, with a default value of "node"; this value can be customized.
14 arch
The architecture of the current CPU: 'arm', 'ia32', or 'x64'.
15 platform
The platform on which the program runs: 'darwin', 'freebsd', 'linux', 'sunos', or 'win32'
16 mainModule
An alternative to require.main. The difference is that if the main module changes at runtime, require.main may continue to return the old module. It can be considered that both refer to the same module.

Example

Create the file main.js with the following code:



// Output to console

process.stdout.write("Hello World!" + "\n");



// Read via parameters

process.argv.forEach(function(val, index, array) {

   console.log(index + ': ' + val);

});



// Get execution path

console.log(process.execPath);





// Platform information

console.log(process.platform);

Execute the main.js file with the following code:



$ node main.js

Hello World!

0: node

1: /web/www/node/main.js

/usr/local/node/0.10.36/bin/node

darwin

Method Reference Manual

Process provides many useful methods to help us better control system interaction:

No. Method & Description
1 abort()
This will cause node to trigger an abort event, causing node to exit and generate a core file.
2 chdir(directory)
Change the directory of the current working process; if the operation fails, an exception is thrown.
3 cwd()
Returns the working directory of the current process
4 exit([code])
End the process with the specified code. If omitted, code 0 will be used.
5 getgid()
 获取进程的群组标识(参见 getgid(2))。获取到的是群组的数字 id,而不是名字。       

 注意:这个函数仅在 POSIX 平台上可用(例如,非Windows 和 Android)。 |

| 6 | setgid(id)
Set the process group ID (see setgid(2)). It can accept a numeric ID or a group name. If a group name is specified, it will block waiting for it to be resolved to a numeric ID.
Note: This function is only available on POSIX platforms (e.g., non-Windows and Android). | | 7 | getuid()
Get the process user ID (see getuid(2)). This is a numeric user id, not a username.
Note: This function is only available on POSIX platforms (e.g., non-Windows and Android). | | 8 | setuid(id)
Set the process user ID (see setuid(2)). Accepts a numeric ID or string name. If a group name is specified, it will block waiting for it to be resolved to a numeric ID.
Note: This function is only available on POSIX platforms (e.g., non-Windows and Android). | | 9 | getgroups()
Returns an array of the process's group IDs. POSIX systems do not guarantee this, but node.js does.
Note: This function is only available on POSIX platforms (e.g., non-Windows and Android). | | 10 | setgroups(groups)
Set the process group ID. This is a privileged operation, so you need root privileges or the CAP_SETGID capability.
Note: This function is only available on POSIX platforms (e.g., non-Windows and Android). | | 11 | initgroups(user, extra_group)
Read /etc/group and initialize the group access list, using all the groups the member belongs to. This is a privileged operation, so you need root privileges or the CAP_SETGID capability.
Note: This function is only available on POSIX platforms (e.g., non-Windows and Android). | | 12 | kill(pid[, signal])
Send a signal to a process. pid is the process id, and signal is a string description of the signal to send. Signal names are strings, such as 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. | | 13 | memoryUsage()
Returns an object describing the memory usage of the Node process, in bytes. | | 14 | nextTick(callback)
Calls the callback function once the current event loop ends. | | 15 | umask([mask])
Sets or reads the process file mode mask. Child processes inherit the mask from the parent process. If the mask parameter is valid, the old mask is returned; otherwise, the current mask is returned. | | 16 | uptime()
Returns the number of seconds Node has been running. | | 17 | hrtime()
Returns the high-resolution time of the current process in the form of a [seconds, nanoseconds] array. It is relative to an arbitrary point in the past. This value is independent of the date and therefore not affected by clock drift. Its main use is to measure program performance through precise time intervals.
You can pass a previous result to the current process.hrtime(), which will return the time difference between the two, used for benchmarking and measuring time intervals. |

Example

Create the file main.js with the following code:



// Output current directory

console.log('当前目录: ' + process.cwd());



// Output current version

console.log('当前版本: ' + process.version);



// Output memory usage

console.log(process.memoryUsage());

Execute the main.js file with the following code:



$ node main.js

当前目录: /web/com/runoob/nodejs

当前版本: v0.10.36

{ rss: 12541952, heapTotal: 4083456, heapUsed: 2157056 }