Node.js Global Objects
In JavaScript, there is a special object called the Global Object, which, along with all its properties, can be accessed anywhere in the program, i.e., global variables.
In browser JavaScript, the global object is typically window
, whereas 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 our application.
Global Objects and Global Variables
The primary role of global
is to act as the host for global variables. According to ECMAScript specifications, a variable is considered global if it meets the following criteria:
- Defined in the outermost scope;
- A property of the global object;
- Implicitly defined variables (variables assigned without being declared).
When you define a global variable, it also becomes a property of the global object, and vice versa. It's important to note that in Node.js, you cannot define variables in the outermost scope because all user code belongs to the current module, and the module itself is not the outermost context.
Note: It's best to avoid using var
to define variables to prevent introducing global variables, as they can pollute the namespace and increase the risk of code coupling.
__filename
__filename represents the file name of the currently executing script. It outputs the absolute path of the file location, which may not be the same as the file name specified in the command line arguments. If used in a module, it returns the path of the module file.
Example
Create a file main.js
with the following code:
// Output the value of the global variable __filename
console.log(__filename);
Execute the main.js
file:
$ node main.js
/web/com/tutorialpro/nodejs/main.js
__dirname
__dirname represents the directory of the currently executing script.
Example
Create a file main.js
with the following code:
// Output the value of the global variable __dirname
console.log(__dirname);
Execute the main.js
file:
$ node main.js
/web/com/tutorialpro/nodejs
setTimeout(cb, ms)
setTimeout(cb, ms) is a global function that executes the specified function (cb) after the specified number of milliseconds (ms). The setTimeout()
function executes the specified function only once.
It returns a handle value representing the timer.
Example
Create a file main.js
with the following code:
function printHello() {
console.log("Hello, World!");
}
// Execute the above function after 2 seconds
setTimeout(printHello, 2000);
Execute the main.js
file:
$ node main.js
Hello, World!
clearTimeout(t)
clearTimeout(t) is a global function used to stop a timer previously created with setTimeout()
. The parameter t is the timer created by the setTimeout()
function.
Example
Create a file main.js
with the following code:
function printHello() {
console.log("Hello, World!");
}
// Execute the above function after 2 seconds
var t = setTimeout(printHello, 2000);
// Clear the timer
clearTimeout(t);
Execute the main.js
file:
$ node main.js
setInterval(cb, ms)
setInterval(cb, ms) is a global function that executes the specified function (cb) every specified number of milliseconds (ms).
It returns a handle value representing the timer. The timer can be cleared using the clearInterval(t) function.
The setInterval()
method will keep calling 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!");
}
// Execute the above function every 2 seconds
setInterval(printHello, 2000);
Execute the main.js
file:
$ node main.js
The above program will output "Hello, World!" every two seconds and will continue to run indefinitely until you press ctrl + c.
console
The console is used to provide standard output for the console. It was originally a debugging tool provided by the JScript engine of Internet Explorer and later became a de facto standard for browsers.
Node.js adopted this standard, providing a console object that behaves consistently with customary practices, used for outputting characters to the standard output stream (stdout) or the standard error stream (stderr).
Console Methods
Below are the methods of the console object:
Number | Method & Description |
---|---|
1 | console.log([data][, ...]) <br>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 representation of this parameter. If there are multiple parameters, it outputs in a format similar to the C language's printf() command. |
2 | console.info([data][, ...]) <br>This command returns informational messages. This command is not much different from console.log, except that in Chrome it only outputs text, while in other browsers it displays a blue exclamation mark. |
3 | console.error([data][, ...]) <br>Outputs error messages. The console displays a red cross when an error occurs. |
4 | console.warn([data][, ...]) <br>Outputs warning messages. The console displays a yellow exclamation mark. |
5 | console.dir(obj[, options]) <br>Inspects an object and displays it in a readable and printable format. |
6 | console.time(label) <br>Outputs the time, indicating the start of timing. |
7 | console.timeEnd(label) <br>Ends the timing, indicating the end of timing. |
8 | console.trace(message[, ...]) <br>Outputs the call stack of the current execution code. This is helpful for testing functions, just add console.trace to the function you want to test. |
9 | console.assert(value[, message][, ...]) <br>Used to determine if 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, the second parameter will be output, otherwise, there will be no result. |
console.log accepts several parameters. If there is only one parameter, it outputs the string representation of this parameter. If there are multiple parameters, it outputs in a format similar to the C language's 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 output will be:
Hello world
byvoid%diovyb
byvoid1991iovyb
console.error(): Same usage as console.log(), but outputs to the standard error stream.
console.trace(): Outputs the current call stack to the standard error stream.
console.trace();
The output will be:
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 named main.js with the following code:
console.info("Program started:");
var counter = 10;
console.log("Count: %d", counter);
console.time("Fetch data");
//
// Execute some code
//
console.timeEnd('Fetch data');
console.info("Program finished.")
Run the main.js file with the following command:
$ node main.js
Program started:
Count: 10
Fetch data: 0ms
Program finished
Process
process is a global variable, an attribute of the global object. It is an object used to describe the current Node.js process status, providing a simple interface with the operating system. It is commonly used when writing native command-line programs. Below are some of the most commonly used member methods of the process object.
Number | Event & Description |
---|---|
1 | exit <br>Triggered when the process is about to exit. |
2 | beforeExit <br>Triggered when node has emptied the event loop and has no other tasks scheduled. Normally, node exits when there are no tasks, but a 'beforeExit' listener can call asynchronous operations, causing node to continue. |
3 | uncaughtException <br>Triggered when an exception bubbles back to the event loop. If an observer is added for the exception, the default action (printing the stack trace and exiting) will not occur. |
4 | Signal Events <br>Triggered when the process receives a signal. See the standard POSIX signal names, such as SIGINT, SIGUSR1, etc. |
Example
Create a file named main.js with the following code:
process.on('exit', function(code) {
// The following code will never execute
setTimeout(function() {
console.log("This code will not run");
}, 0);
console.log('Exit code:', code);
});
console.log("Program execution complete");
Execute the main.js file with the following command:
$ node main.js
Program execution complete
Exit code: 0
Exit Status Codes
Status Code | Name & Description |
---|---|
1 | Uncaught Fatal Exception <br>An uncaught exception that was not handled by domains or the uncaughtException handler. |
2 | Unused <br>Reserved, reserved by Bash for internal misuse |
3 | Internal JavaScript Parse Error <br>A parsing error occurred when starting the Node process with the JavaScript source code. Very rare, only when developing Node. |
4 | Internal JavaScript Evaluation Failure <br>The Node process started with the JavaScript source code failed to evaluate a function. Very rare, only when developing Node. |
5 | Fatal Error <br>A fatal, unrecoverable error in V8. Typically printed to stderr with the content: FATAL ERROR |
6 | Non-function Internal Exception Handler <br>An uncaught exception, where the internal exception handler is set to a non-function and cannot be called. |
7 | Internal Exception Handler Run-Time Failure <br>An uncaught exception, where the exception handler itself throws an exception. For example, if process.on('uncaughtException') or domain.on('error') throws an exception. |
8 | Unused <br>Reserved, in previous versions of Node.js, exit code 8 sometimes represented an uncaught exception. |
9 | Invalid Argument <br>An unknown parameter may have been given, or a parameter without a value. |
10 | Internal JavaScript Run-Time Failure <br>An error was thrown when starting the Node process with the JavaScript source code. Very rare, only when developing Node. |
12 | Invalid Debug Argument <br>The parameters --debug and/or --debug-brk were set, but an incorrect port was chosen. |
128 | Signal Exits <br>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 in the high bits. |
Process Properties
Process provides many useful properties to better control system interaction:
Number | Property & Description |
---|---|
1 | stdout <br>Standard output stream. |
2 | stderr <br>Standard error stream. |
3 | stdin <br>Standard input stream. |
4 | argv <br>The argv property returns an array composed of the command line arguments when executing the script. The first member is always node, the second is the script file name, and the remaining members are the parameters of the script file. |
5 | execPath <br>Returns the absolute path of the Node binary file that is executing the current script. |
6 | execArgv <br>Returns an array of command-line arguments that were passed between the Node executable file and the script file when the script was executed from the command line. |
7 | env <br>Returns an object containing the current shell's environment variables. |
8 | exitCode <br>The code that the process exits with, if the process exits gracefully without specifying a code via process.exit() . |
9 | version <br>The version of Node, such as v0.10.18. |
10 | versions <br>An object containing the versions of Node and its dependencies. |
11 | config <br>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 <br>The process ID of the current process. |
13 | title <br>The process name, with a default value of "node", which can be customized. |
14 | arch <br>The architecture of the current CPU: 'arm', 'ia32', or 'x64'. |
15 | platform <br>The platform system on which the program is running: 'darwin', 'freebsd', 'linux', 'sunos', or 'win32'. |
16 | mainModule <br>An alternative to require.main . The difference is that if the main module changes at runtime, require.main might continue to return the old module. It can be considered that both refer to the same module. |
Example
Create a file named main.js
with the following code:
// Output to the terminal
process.stdout.write("Hello World!" + "\n");
// Read through arguments
process.argv.forEach(function(val, index, array) {
console.log(index + ': ' + val);
});
// Get the execution path
console.log(process.execPath);
// Platform information
console.log(process.platform);
Execute the main.js
file with the following command:
$ 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
The Process object provides many useful methods to better control system interactions:
Number | Method & Description |
---|---|
1 | abort() <br>This will cause Node to trigger an abort event, causing Node to exit and generate a core file. |
2 | chdir(directory) <br>Changes the current working directory of the process. Throws an exception if the operation fails. |
3 | cwd() <br>Returns the current working directory of the process. |
4 | exit([code]) <br>Exits the process with the specified code. If omitted, it will use the code 0. |
5 | getgid() <br>Gets the group identity of the process (see getgid(2)). This returns the numeric group ID, not the name. <br>Note: This function is only available on POSIX platforms (e.g., not on Windows and Android). |
6 | setgid(id) <br>Sets the group identity of the process (see setgid(2)). It can take a numeric ID or a group name. If a group name is specified, it blocks until it resolves to a numeric ID. <br>Note: This function is only available on POSIX platforms (e.g., not on Windows and Android). |
7 | getuid() <br>Gets the user identity of the process (see getuid(2)). This returns the numeric user ID, not the username. <br>Note: This function is only available on POSIX platforms (e.g., not on Windows and Android). |
8 | setuid(id) <br>Sets the user identity of the process (see setuid(2)). It can take a numeric ID or a username. If a group name is specified, it blocks until it resolves to a numeric ID. <br>Note: This function is only available on POSIX platforms (e.g., not on Windows and Android). |
9 | getgroups() <br>Returns an array of supplementary group IDs. POSIX does not guarantee that this array will be present, but Node.js ensures it is. <br>Note: This function is only available on POSIX platforms (e.g., not on Windows and Android). |
10 | setgroups(groups) <br>Sets the group IDs for the process. This is an authorization operation, so you need to have root privileges or have the CAP_SETGID capability. <br>Note: This function is available only on POSIX platforms (e.g., non-Windows and Android). |
11 | initgroups(user, extra_group) <br>Reads /etc/group and initializes the group access list, using all groups of which the user is a member. This is an authorization operation, so you need to have root privileges or have the CAP_SETGID capability. <br>Note: This function is available only on POSIX platforms (e.g., non-Windows and Android). |
12 | kill(pid[, signal]) <br>Sends a signal to a process. pid is the process ID, and signal is the string description of the signal to be sent. Signal names are strings, such as 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. |
13 | memoryUsage() <br>Returns an object describing the memory usage of the Node process in bytes. |
14 | nextTick(callback) <br>Calls the callback function once the current event loop ends. |
15 | umask([mask]) <br>Sets or reads the process file mask. The child process inherits the mask from the parent process. If the mask parameter is valid, it returns the old mask. Otherwise, it returns the current mask. |
16 | uptime() <br>Returns the number of seconds Node has been running. |
17 | hrtime() <br>Returns the current high-resolution real time of the process in the form of an array [seconds, nanoseconds]. It is relative to an arbitrary time in the past. This value is not related to the date and is therefore not affected by clock drift. It is primarily used to measure precise time intervals for program performance. <br>You can pass the previous result to the current process.hrtime() to get the time difference, which is useful for benchmarking and measuring time intervals. |
Example
Create a file main.js with the following code:
// Output the current directory
console.log('Current directory: ' + process.cwd());
// Output the current version
console.log('Current version: ' + process.version);
// Output memory usage
console.log(process.memoryUsage());
Execute the main.js file with the following command:
$ node main.js
Current directory: /web/com/tutorialpro/nodejs
Current version: v0.10.36
{ rss: 12541952, heapTotal: 4083456, heapUsed: 2157056 }