Node.js global objects


There is a special object in JavaScript called the global object (Global Object). It and all its properties can be accessed anywhere in the program, that is, global variables.

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

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


Global objects and global variables

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

  • Variables defined in the outermost layer;

  • Properties of the global object;

  • Implicitly defined variables (undefined variables with direct assignment).

When you define a global variable, the variable will also become a property of the global object, and vice versa. Need to note Interestingly, in Node.js you cannot define variables at the outermost level, because all user code belongs to the current module. The module itself is not the outermost context.

Note: Always use var to define variables to avoid introducing global variables, because global variables will contaminate Namespaces increase the risk of code coupling.


__filename

__filename represents the file name of the currently executing script. It will output the absolute path of the file location, and it may not be the same as the file name specified by the command line parameter. If in a module, the returned value is the path to the module file.

Example

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

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

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

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

__dirname

__dirname indicates the directory where the currently executing script is located.

Example

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

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

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

$ node main.js
/web/com/php/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 the file main.js, the code is as follows:

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

Execute 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 through setTimeout(). Parameter t is the calculator created by the setTimeout() function.

Example

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

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

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

Execute 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 use the clearInterval(t) function to clear the timer.

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

Example

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

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

Execute 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 be executed permanently until you press the ctrl + c button.


console

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

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

console method

The following are the methods of the console object:

Serial numberMethod & Description
1console.log([data][, ...])
Print characters to the standard output stream and end with a newline character. This method receives several parameters. If there is only one parameter, the string form of this parameter is output. If there are multiple arguments, the output is in a format similar to the C language printf() command.
2console.info([data][, ...])
PThe function of this command is to return information Sex message, this command is not much different from console.log, except that only text will be output in chrome, and a blue exclamation point will be displayed for the rest.
3console.error([data][, ...])
Output error message. The console will display a red cross when an error occurs.
4console.warn([data][, ...])
Output warning message. A yellow exclamation point appears on the console.
5console.dir(obj[, options])
is used to inspect an object and Presented in an easy-to-read and printable format.
6console.time(label)
Output time, indicating the start of timing.
7console.timeEnd(label)
End time, indicating the end of timing.
8console.trace(message[, ...])
The call path of the currently executed code in the stack , this test function is very helpful to run, just add console.trace to the function you want to test.
9console.assert(value[, message][, ...])
is used to judge an expression Whether the expression or variable is true, it takes two parameters, the first parameter is the expression, and the second parameter is the string. The second parameter will be output only if the first parameter is false, otherwise there will be no result.
console.log(): Prints characters to the standard output stream and ends with a newline character.


console.log Accept several parameters, if there is only one parameter, the string form of this parameter is output. If there are multiple parameters, then Output in a format similar to the C language printf() command.

The first parameter is a string, if not parameter, just print 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(): The usage is the same as console.log(), but it is output to the standard error stream.

  • console.trace(): Output 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)

Instance

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

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

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

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

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

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

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

process

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

It is an object used to describe the current Node.js process status and provides a simple interface with the operating system. Usually when you write a local command line program, you have to deal with it. Some of the most commonly used member methods of the process object will be introduced below.

##1234

Example

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

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

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

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

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

Exit status code

The exit status code is as follows:

Serial NumberEvent & Description
exitFired when the process is ready to exit.
beforeExitThis event is triggered when node clears the event loop and there are no other arrangements. Normally, node exits when no processes are scheduled, but the 'beforeExit' listener can be called asynchronously so that node continues execution.
uncaughtExceptionThis event is triggered when an exception bubbles back to the event loop. If a monitor is added to the exception, the default action (print the stack trace and exit) will not occur.
Signal event is triggered when the process receives a signal. For the signal list, see the standard POSIX signal names, such as SIGINT, SIGUSR1, etc.
##67891012>128

Process attributes

Process provides many useful attributes to facilitate us to better control the interaction of the system:

Status CodeName & Description
1Uncaught Fatal Exception
There was an uncaught exception and it was not handled by the domain or uncaughtException handler.
2Unused
Reserved
3Internal JavaScript Parse Error
The source code of JavaScript causes a parsing error when starting the Node process. Very rare and only available when developing Node.
4Internal JavaScript Evaluation Failure
The source code of JavaScript starts the Node process and returns a function failure during evaluation. Very rare and only available when developing Node.
5Fatal Error
A fatal and unrecoverable error in V8. Typically printed to stderr, the content is: FATAL ERROR
Non-function Internal Exception HandlerUncaught exception, internal The exception handling function is somehow set to on-function and cannot be called.
Internal Exception Handler Run-Time Failure Uncaught exception, and the exception handling function threw it by itself during processing abnormal. For example, if process.on('uncaughtException') or domain.on('error') throws an exception.
UnusedReserved
Invalid ArgumentIt may be that an unknown parameter is given, or the parameter given has no value.
Internal JavaScript Run-Time FailureThe source code of JavaScript throws an error when starting the Node process. It is very rare and only occurs. Only available when developing Node.
Invalid Debug Argument The parameters --debug and/or --debug-brk were set, but the wrong one was selected port.
Signal Exits If Node receives a fatal signal, such as SIGKILL or SIGHUP, the exit code is 128 plus signal code. This is standard Unix practice, with the exit signal code placed high.
Serial number.Properties & Description
1stdout
Standard output stream.
2stderr
Standard error stream.
3stdin
Standard input stream.
4argv
The argv property returns an array consisting of various parameters when executing the script from the command line. Its first member is always node, the second member is the script file name, and the remaining members are the parameters of the script file.
5execPath
Returns the absolute path to the Node binary that executes the current script.
6execArgv
Returns an array, the members are the Node executable files and script files when executing the script under the command line command line parameters.
7env
Returns an object whose members are the environment variables of the current shell
8exitCode
The code when the process exits. If the process exits through process.exit(), there is no need to specify the exit code.
9version
The version of Node, such as v0.10.18.
10versions
A property that contains the node version and dependencies.
11config
An object containing the javascript configuration options used to compile the current node execution file. It is the same "config.gypi" file generated by running the ./configure script.
12pid
The process ID of the current process.
13title
Process name, the default value is "node", this value can be customized.
14arch
Current CPU architecture: 'arm', 'ia32' or 'x64'.
15platform
The platform system where the running program is located 'darwin', 'freebsd', 'linux', 'sunos' Or alternative to 'win32'
16mainModule
require.main. The difference is that if the main module changes during runtime, require.main may continue to return the old module. It can be considered that these two refer to the same module.

Example

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

// 输出到终端
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, the code is as follows:

$ 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 us to better control system interaction:

Serial numberMethod & Description
1abort()
This will cause node to trigger the abort event. Will cause node to exit and generate a core file.
2chdir(directory)
Change the directory of the current working process and throw an exception if the operation fails.
3cwd()
Returns the working directory of the current process
4 exit([code])
Use the specified code to end the process. If omitted, code 0 will be used.
5getgid()
Get the group ID of the process (see getgid(2)). Get the numeric id of the group, not the name.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
6setgid(id)
Set the group ID of the process (see setgid(2)). Can receive numeric ID or group name. If a group name is specified, it will block waiting for resolution to a numeric ID.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
7getuid()
Get the user ID of the process (see getuid(2)). This is a numeric user ID, not a username.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
8setuid(id)
Set the user ID of the process (see setuid(2)). Receives a numeric ID or string name. If a group name is specified, it will block waiting for parsing into a numeric ID.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
9getgroups()
Returns the group iD array of the process. There is no guarantee that POSIX system will have it, but node.js guarantees it.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
10setgroups(groups)
Set the group ID of the process. This is an authorized operation, so you need to have root privileges, or have the CAP_SETGID capability.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
11initgroups(user, extra_group)
Read /etc/group and initialize the group access list, using members All groups you are in. This is an authorized operation, so you need to have root privileges, or have the CAP_SETGID capability.
Note: This function is only available on POSIX platforms (i.e., non-Windows and Android).
12kill(pid[, signal])
Send a signal to the process. pid is the process id, and signal is sent A string description of the signal. The signal name is a string, such as 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
13memoryUsage()
Returns an object describing the memory status used by the Node process, in bytes.
14nextTick(callback)
Once the current event loop ends, call the return function.
15umask([mask])
Set or read the mask of the process file. The child process inherits the mask from the parent process. If the mask parameter is valid, the old mask is returned. Otherwise, returns the current mask.
16uptime()
Returns the number of seconds that Node has been running.
17hrtime()
Returns the high-resolution time of the current process in the form of [seconds, nanoseconds] array. It is an arbitrary event relative to the past. This value is date independent and therefore not affected by clock drift. The main purpose is to measure the performance of the program through precise time intervals.
You can pass the previous result to the current process.hrtime(), which will return the time difference between the two, which can be used to benchmark and measure the time interval.

Example

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

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

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

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

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

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