Nodejs Global Object
JavaScript has a special object called the Global Object. Its properties and methods can be accessed from anywhere in the program, making them global variables.
In browser JavaScript, `window` is typically the global object. 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 Object and Global Variables
The fundamental role of `global` is to act as the host for global variables. According to the ECMAScript specification, a variable is considered global if it meets one of the following conditions:
* Defined in the outermost scope;
* A property of the global object;
* Implicitly defined (a variable assigned without being declared).
When you define a global variable, that variable also becomes a property of the global object, and vice versa. 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 is best to avoid using `var` to define variables to prevent introducing global variables, as they 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, which may not be the same as the filename specified in the command-line arguments. If within a module, the returned value is the path of the module file.
### Example
Create a file `main.js` with the following code:
```javascript
// Output the value of the global variable __filename
console.log( __filename );
Execute the `main.js` file as follows:
```bash
$ node main.js
/web/com//nodejs/main.js
* * *
## __dirname
**__dirname** represents the directory of the script currently being executed.
### Example
Create a file `main.js` with the following code:
```javascript
// Output the value of the global variable __dirname
console.log( __dirname );
Execute the `main.js` file as follows:
```bash
$ node main.js
/web/com//nodejs
* * *
## setTimeout(cb, ms)
The global function **setTimeout(cb, ms)** executes the specified function (`cb`) after a specified number of milliseconds (`ms`). `setTimeout()` executes the specified function only once.
It returns a handle value representing the timer.
### Example
Create a file `main.js` with the following code:
```javascript
function printHello(){
console.log( "Hello, World!");
}
// Execute the above function after two seconds
setTimeout(printHello, 2000);
Execute the `main.js` file as follows:
```bash
$ node main.js
Hello, World!
* * *
## clearTimeout(t)
The global function **clearTimeout( t )** is used to stop a timer previously created by `setTimeout()`. The parameter **t** is the timer created by the `setTimeout()` function.
### Example
Create a file `main.js` with the following code:
```javascript
function printHello(){
console.log( "Hello, World!");
}
// Execute the above function after two seconds
var t = setTimeout(printHello, 2000);
// Clear the timer
clearTimeout(t);
Execute the `main.js` file as follows:
```bash
$ node main.js
* * *
## setInterval(cb, ms)
The global function **setInterval(cb, ms)** executes the specified function (`cb`) repeatedly at a specified interval of milliseconds (`ms`).
It returns a handle value representing the timer. You can use the **clearInterval(t)** function to clear the timer.
The `setInterval()` method will call the function repeatedly until `clearInterval()` is called or the window is closed.
### Example
Create a file `main.js` with the following code:
```javascript
function printHello(){
console.log( "Hello, World!");
}
// Execute the above function every two seconds
setInterval(printHello, 2000);
Execute the `main.js` file as follows:
```bash
$ node main.js
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
β¦β¦
The program above will output "Hello, World!" every two seconds and will continue to run indefinitely until you press **ctrl + c**.
* * *
## console
`console` is used to provide standard console output. It is a debugging tool provided by the JScript engine in Internet Explorer and later became an implementation standard for browsers.
Node.js adopted this standard, providing a `console` object consistent with familiar behavior, used to output characters to the standard output stream (stdout) or standard error stream (stderr).
### console Methods
The following are methods of the `console` object:
| No. | Method & Description |
| --- | --- |
| 1 | **console.log([, ...])** 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. |
| 2 | **console.info([, ...])** This command is used to return informational messages. It is not much different from `console.log`, except that in Chrome it only outputs text, while in others it displays a blue exclamation mark. |
| 3 | **console.error([, ...])** Outputs error messages. The console displays a red cross when an error occurs. |
| 4 | **console.warn([, ...])** 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 time, indicating the start of timing. |
| 7 | **console.timeEnd(label)** Ends time, indicating the end of timing. |
| 8 | **console.trace(message[, ...])** The call path of the currently executing code in the stack. This is very helpful for testing functions; just add `console.trace` inside the function you want to test. |
| 9 | **console.assert(value[, message][, ...])** Used to determine if 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 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 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.
```javascript
console.log('Hello world');
console.log('byvoid%diovyb');
console.log('byvoid%diovyb', 1991);
The output is:
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.
```javascript
console.trace();
The output 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 a file `main.js` with the following code:
```javascript
console.info("Program starts executing:");
var counter = 10;
console.log("Count: %d", counter);
console.time("Fetch data");
// Execute some code
console.timeEnd('Fetch data');
console.info("Program execution completedγ")
Execute the `main.js` file as follows:
```bash
$ node main.js
Program starts executing:
Count: 10
Fetch data: 0ms
Program execution completed
* * *
## 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 to the operating system. When writing local command-line programs, you will often interact with it. Below are some of the most commonly used member methods of the `process` object.
| No. | Event & Description |
| --- | --- |
| 1 | **exit** Triggered when the process is ready to exit. |
| 2 | **beforeExit** Triggered when Node clears the event loop and there are no other tasks scheduled. Typically, Node exits when there are no tasks scheduled, but the 'beforeExit' listener can be called asynchronously, allowing Node to continue execution. |
| 3 | **uncaughtException** Triggered when an exception bubbles back to the event loop. If a monitor is added to the exception, the default action (printing stack trace and exiting) will not occur. |
| 4 | **Signal Events** Triggered when the process receives a signal. See the standard POSIX signal names for a list of signals, such as SIGINT, SIGUSR1, etc. |
### Example
Create a file `main.js` with the following code:
```javascript
process.on('exit', function(code) {
// The following code will never execute
setTimeout(function() {
console.log("This code will not be executed");
}, 0);
console.log('Exit code is:', code);
});
console.log("Program execution finished");
Execute the `main.js` file as follows:
```bash
$ node main.js
Program execution finished
Exit code is: 0
### Exit Status Codes
The exit status codes are as follows:
| Status Code | Name & Description |
| --- | --- |
| 1 | **Uncaught Fatal Exception** An uncaught exception that was not handled by a domain or uncaughtException handler. |
| 2 | **Unused** Reserved by Bash for built-in misuse. |
| 3 | **Internal JavaScript Parse Error** The JavaScript source code caused a parse error when starting the Node process. Very rare, only occurs when developing Node. |
| 4 | **Internal JavaScript Evaluation Failure** The JavaScript source code started the Node process, but evaluation failed. Very rare, only occurs when developing Node. |
| 5 | **Fatal Error** A fatal, unrecoverable error in V8. Usually printed to stderr with the content: FATAL ERROR. |
| 6 | **Non-function Internal Exception Handler** An uncaught exception, and 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** Possibly an unknown parameter was given, or the parameter had no value. |
| 10 | **Internal JavaScript Run-Time Failure** The JavaScript source code threw 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 chosen. |
| 128 | **Signal Exits** If Node receives a fatal signal, such as SIGKILL or SIGHUP, the exit code is 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 facilitate better control of system interaction:
| No. | Property & Description |
| --- | --- |
| 1 | **stdout** Standard output stream. |
| 2 | **stderr** Standard error stream. |
| 3 | **stdin** Standard input stream. |
| 4 | **argv** The `argv` property returns an array composed of the various parameters when executing a script from the command line. Its first member is always `node`, the second is the script filename, and the remaining members are the script file's arguments. |
| 5 | **execPath** Returns the absolute path of the Node binary file 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 executing a script from the command line. |
| 7 | **env** Returns an object whose members are the environment variables of the current shell. |
| 8 | **exitCode** The code when the process exits. If the process exits via `process.exit()`, the exit code does not need to be specified. |
| 9 | **version** The version of Node, e.g., v0.10.18. |
| 10 | **versions** A property containing the Node version and its dependencies. |
| 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, default is "node", and this value can be customized. |
| 14 | **arch** The architecture of the current CPU: 'arm', 'ia32', or 'x64'. |
| 15 | **platform** The platform system where the program is running: '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` might continue to return the old module. It can be considered that both reference the same module. |
### Example
Create a file `main.js` with the following code:
```javascript
// Output to terminal
process.stdout.write("Hello World!" + "n");
// Read via arguments
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 as follows:
```bash
$ 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 facilitate better control of system interaction:
| No. | Method & Description |
| --- | --- |
| 1 | **abort()** This will cause Node to trigger the 'abort' event. It will cause Node to exit and generate a core file. |
| 2 | **chdir(directory)** Changes the current working directory of the process. Throws an exception if the operation fails. |
| 3 | **cwd()** Returns the current working directory of the process. |
| 4 | **exit()** Ends the process with the specified `code`. If omitted, code 0 will be used. |
| 5 | **getgid()** Gets the group identity of the process (see getgid(2)). The returned value is the numeric group ID, not the name. Note: This function is only available on POSIX platforms (e.g., not Windows and Android). |
| 6 | **setgid(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 will block until it is resolved to a numeric ID. Note: This function is only available on POSIX platforms (e.g., not Windows and Android). |
| 7 | **getuid()** 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., not Windows and Android). |
| 8 | **setuid(id)** Sets the user identity of the process (see setuid(2)). Accepts a numeric ID or a string name. If a group name is specified, it will block until it is resolved to a numeric ID. Note: This function is only available on POSIX platforms (e.g., not 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., not Windows and Android). |
| 10 | **setgroups(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., not Windows and Android). |
| 11 | **initgroups(user, extra_group)** Reads /etc/group and initializes the group access list, using all groups of which the user is a member. 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., not Windows and Android). |
| 12 | **kill(pid[, signal])** Sends a signal to a process. `pid` is the process ID, and `signal` is the 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()** Sets or reads the file mode creation mask of the process. Child processes inherit the mask from the parent process. If the `mask` parameter is valid, returns the old mask. Otherwise, returns the current mask. |
| 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 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, used for benchmarking and measuring time intervals. |
### Example
Create a file `main.js` with the following code:
```javascript
// Output current directory
console.log('Current directory: ' + process.cwd());
// Output current version
console.log('Current version: ' + process.version);
// Output memory usage
console.log(process.memoryUsage());
Execute the `main.js` file as follows:
```bash
$ node main.js
Current directory: /web/com//nodejs
Current version: v0.10.36
{ rss: 12541952, heapTotal: 4083456, heapUsed: 2157056 }
YouTip