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, i.e., 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 needing to include it in the application.


Global Objects and Global Variables

The most fundamental role of global is to serve as the host for global variables. According to the ECMAScript definition, variables that meet the following conditions are global variables:

  • Variables defined at the outermost level;
  • Properties of the global object;
  • Implicitly defined variables (variables assigned directly without definition).

When you define a global variable, that variable also becomes a property of the global object, and vice versa. It should be noted that in Node.js you cannot define variables 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 to avoid introducing global variables, because global variables pollute the namespace and increase the coupling risk of code.


__filename

__filenameRepresents the filename of the script currently being executed. It will output the absolute path of the file's location, and it may not be the same as the filename specified by the command-line arguments. If in a module, the returned value is the path of the module file.

Example

Create a file main.js with the following code:

// 输出全局变量 __filename 的值
console.log( __filename );

Run the main.js file, the code is as follows:

$ node main.js
/web/com/example/nodejs/main.js

__dirname

__dirnameRepresents the directory where the currently executing script is located.

Example

Create a file main.js with the following code:

// 输出全局变量 __dirname 的值
console.log( __dirname );

Run the main.js file, the code is as follows:

$ node main.js
/web/com/example/nodejs

setTimeout(cb, ms)

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

Returns a handle value representing the timer.

Example

Create a file main.js with the following code:

function printHello(){
   console.log( "Hello, World!");
}
// 两秒后执行以上函数
setTimeout(printHello, 2000);

Run the main.js file, the code is as follows:

$ node main.js
Hello, World!

clearTimeout(t)

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

Example

Create a file main.js with the following code:

function printHello(){
   console.log( "Hello, World!");
}
// 两秒后执行以上函数
var t = setTimeout(printHello, 2000);

// 清除定时器
clearTimeout(t);

Run the main.js file, the code is as follows:

$ 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 useclearInterval(t)the function to clear the timer.

The setInterval() method will continuously call the function until clearInterval() is called or the window is closed.

Example

Create a file main.js with the following code:

function printHello(){
   console.log( "Hello, World!");
}
// 两秒后执行以上函数
setInterval(printHello, 2000);

Run the main.js file, the code is as follows:

$ node main.js
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! ……

The above program will output "Hello, World!" every two seconds, and will keep executing forever until you pressctrl + cthe button.


console

console is used to provide standard console output. It is a debugging tool provided by Internet Explorer's JScript engine, and later gradually became the implementation standard for browsers.

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

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 in a format similar to the C language printf() command.

The first parameter is a string. If there are no parameters, it only prints a newline.

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

The running result is:

Hello world 
byvoid%diovyb 
byvoid1991iovyb 
  • console.error(): Same usage as console.log(), except it outputs to the standard error stream.
  • console.trace(): Outputs the current call stack to the standard error stream.
console.trace();

The running result is:

Trace: 
at Object.<anonymous> (/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 a file main.js with the following code:

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

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

console.time("获取数据");
//
// 执行一些代码
// 
console.timeEnd('获取数据');

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

Run the main.js file, the code is as follows:

$ node main.js
程序开始执行:
计数: 10
获取数据: 0ms
程序执行完毕

process

process is a global variable, i.e., a property of the global object.

It is an object used to describe the current Node.js process state, providing a simple interface with the operating system. Usually when you write local command-line programs, you inevitably need to deal with it. The following will introduce some of the most commonly used member methods of the process object.

No.Event & Description
1exit
Triggered when the process is about to exit.
2beforeExit
This event is triggered when node empties the event loop and has no other arrangements. Generally, node exits when there are no process arrangements, but 'beforeExit' listeners can be called asynchronously, so node will continue executing.
3uncaughtException
Triggered when an exception bubbles back to the event loop. If a listener is added for the exception, the default operation (printing stack trace and exiting) will not happen.
4Signal Event
Triggered when the process receives a signal. For the signal list, see the standard POSIX signal names, such as SIGINT, SIGUSR1, etc.

Example

Create a file main.js with the following code:

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

  // 以下代码永远不会执行
  setTimeout(function() {
    console.log("该代码不会执行");
  }, 0);
  
  console.log('退出码为:', code);
});
console.log("程序执行结束");

Run the main.js file, the code is as follows:

$ node main.js
程序执行结束
退出码为: 0

Exit Status Codes

The exit status codes are as follows:

Status CodeName & Description
1Uncaught Fatal Exception
There is an uncaught exception, and it has not been handled by a domain or an uncaughtException handler.
2Unused
Reserved, reserved by Bash for built-in misuse.
3Internal JavaScript Parse Error
A parsing error caused when starting the Node process with JavaScript source code. Very rare, only occurs when developing Node.
4Internal JavaScript Evaluation Failure
A failure to return a function when evaluating JavaScript source code to start the Node process. Very rare, only occurs when developing Node.
5Fatal Error
A fatal and unrecoverable error in V8. Usually printed to stderr, with the content: FATAL ERROR.
6Non-function Internal Exception Handler
Uncaught exception, and for some reason the internal exception handler function is set to non-function and cannot be called.
7Internal Exception Handler Run-Time Failure
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.
8Unused
Reserved. In previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception.
9Invalid Argument
Possibly an unknown argument was given, or the argument given had no value.
10Internal JavaScript Run-Time Failure
An error thrown when the JavaScript source starts the Node process; very rare, and only occurs when developing Node itself.
12Invalid Debug Argument
The --debug and/or --debug-brk option was set, but an incorrect port was chosen.
128Signal Exits
If Node receives a fatal signal, such as SIGKILL or SIGHUP, then the exit code is 128 plus the signal code. This is standard Unix practice, placing the exit signal code in the high bits.

Process Properties

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

No.Property & Description
1stdout
Standard output stream.
2stderr
Standard error stream.
3stdin
Standard input stream.
4argv
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 member is the script file name, and the remaining members are the script file's arguments.
5execPath
Returns the absolute path of the Node binary file executing the current script.
6execArgv
Returns an array whose members are the command-line arguments between the Node executable file and the script file when the script is executed from the command line.
7env
Returns an object whose members are the environment variables of the current shell.
8exitCode
The exit code when the process exits. If the process exits through process.exit(), there is no need to specify an exit code.
9version
Node's version, such as v0.10.18.
10versions
A property that contains Node's version and dependencies.
11config
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.
12pid
The process ID of the current process.
13title
The process name, with a default value of "node"; this value can be customized.
14arch
The current CPU architecture: 'arm', 'ia32', or 'x64'.
15platform
The platform system on which the program runs: 'darwin', 'freebsd', 'linux', 'sunos', or 'win32'.
16mainModule
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 reference the same module.

Example

Create a file named main.js with the following code:

// 输出到终端
process.stdout.write("Hello World!" + "\n");

// 通过参数读取
process.argv.forEach(function(val, index, array) {
   console.log(index + ': ' + val);
});

// 获取执行路径
console.log(process.execPath);


// 平台信息
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

Methods Reference

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

No.Method & Description
1abort()
This will cause Node to trigger the abort event. It will cause Node to exit and generate a core file.
2chdir(directory)
Changes the directory of the current working process; throws an exception if the operation fails.
3cwd()
Returns the working directory of the current process.
4exit([code])
Ends the process with the specified code. If omitted, code 0 will be used.
5getgid()
Gets the group identity of the process (see getgid(2)). The numeric group id is obtained, not the name.
Note: This function is only available on POSIX platforms (e.g., non-Windows and non-Android).
6setgid(id)
Sets the group identity of the process (see setgid(2)). It can accept a numeric ID or a group name. If a group name is specified, it blocks while waiting to resolve it to a numeric ID.
Note: This function is only available on POSIX platforms (e.g., non-Windows and non-Android).
7getuid()
Gets the user identity of the process (see getuid(2)). This is the numeric user id, not the username.
Note: This function is only available on POSIX platforms (e.g., non-Windows and non-Android).
8setuid(id)
Sets the user identity of the process (see setuid(2)). It accepts a numeric ID or a string name. If a group name is specified, it blocks while waiting to resolve it to a numeric ID.
Note: This function is only available on POSIX platforms (e.g., non-Windows and non-Android).
9getgroups()
Returns an array of the process's group IDs. POSIX systems do not guarantee their presence, but node.js does guarantee it.
Note: This function is only available on POSIX platforms (e.g., non-Windows and non-Android).
10setgroups(groups)
Sets the process's group IDs. 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 non-Android).
11initgroups(user, extra_group)
Reads /etc/group and initializes the group access list, using all groups to which the member belongs. 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 non-Android).
12kill(pid[, signal])
Sends a signal to the process. pid is the process id, and signal is the string description of the signal being sent. Signal names are strings, such as 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
13memoryUsage()
Returns an object describing the memory usage of the Node process, in bytes.
14nextTick(callback)
Calls the callback function once the current event loop ends.
15umask([mask])
Sets or reads the process file mask (umask). Child processes inherit the mask from the parent process. If the mask argument is valid, the old mask is returned. Otherwise, the current mask is returned.
16uptime()
Returns the number of seconds Node has been running.
17hrtime()
Returns the high-resolution time of the current process as an array of [seconds, nanoseconds]. It is relative to an arbitrary event in the past. This value is unrelated to the date, so it is not affected by clock drift. Its main purpose is to measure program performance through precise time intervals.
You can pass the previous result to the current process.hrtime(), which will return the time difference between the two, for benchmarking and measuring time intervals.

Example

Create a file named main.js with the following code:

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

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

// 输出内存使用情况
console.log(process.memoryUsage());

Execute the main.js file with the following code:

$ node main.js
当前目录: /web/com/example/nodejs
当前版本: v0.10.36
{ rss: 12541952, heapTotal: 4083456, heapUsed: 2157056 }
Other Extensions