Latest web development tutorials

Node.js global object

JavaScript has a special object, called a global object (Global Object), it and all its attributes can be accessed anywhere in the program, the global variable.

Browser JavaScript usually is global window object, the global object Node.js is global, all global variables (except global itself) are the property of global object.

In Node.js us direct access to the global properties, without the need to include it in the application.


Global objects and global variables

The most fundamental global role as a global variable host. By definition ECMAScript meet the following conditions are global variables:

  • Outermost defined variable;
  • Properties of the global object;
  • Variable implicitly defined (direct assignment undefined variables).

When you define a global variable, the variable will also become the property of the global object, and vice versa. Note that, in Node.js you can not define variables in the outermost, because all user codes are part of the current module, and the module itself is not the outermost context.

Note: always use var to define variables in order to avoid the introduction of a global variable, because global variables will pollute the namespace, increase the risk of coupling code.


__filename

__filename indicates the file name of the script currently being executed.Absolute path to the location where it will be the output file, and the command-line parameter and specify the file name is not necessarily the same. If in the module, the value returned is the path to the module file.

Examples

Create a file main.js, code as follows:

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

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

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

__dirname

__dirname represents the currently executing script directory is located.

Examples

Create a file main.js, code as follows:

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

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

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

setTimeout (cb, ms)

setTimeout (cb, ms) global function performs the specified function after a specified number of milliseconds (ms) Number (cb).: SetTimeout () function is specified only once.

It returns a handle value represents the timer.

Examples

Create a file main.js, code as follows:

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

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

$ node main.js
Hello, World!

clearTimeout (t)

clearTimeout (t) is used to stop a global function before passing setTimeout () to create a timer.Parametert by setTimeout () function to create a calculator.

Examples

Create a file main.js, code as follows:

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

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

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

$ node main.js

setInterval (cb, ms)

setInterval (cb, ms) global function performs the specified function after a specified number of milliseconds (ms) Number (cb).

It returns a handle value represents the timer. You can use theclearInterval (t) function to clear the timer.

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

Examples

Create a file main.js, code as follows:

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

Executive 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 once every two seconds "Hello, World!", And will be permanently execution continues until you pressctrl + c button.


console

console console for providing standard output, which is the debugging tools provided by Internet Explorer's JScript engine, later becoming the de facto standard browser.

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

console method

The following is the console object:

No. Method & description
1 console.log ([data] [, ... ])
To the standard output stream printing characters and end with a newline. This method takes several parameters, if there is only one parameter, the output string of this parameter. If there are multiple arguments, places like the C language printf () command output format.
2 console.info ([data] [, ... ])
P is the role of the command returns an informational message, the command is console.log difference is not large, in addition to the chrome will only output the text, the rest will show a blue exclamation point.
3 console.error ([data] [, ... ])
Output an error message. Console will be displayed in red when an error occurs fork.
4 console.warn ([data] [, ... ])
Warning message is output. Console appears with a yellow exclamation point.
5 console.dir (obj [, options])
An object used to check (inspect), and easy-to-read display and print formats.
6 console.time (label)
The output of the time, the start time.
7 console.timeEnd (label)
End time, indicating the end of timing.
8 console.trace (message [, ...])
Code is currently executing the call path in the stack, run this test function is helpful, just want to test the function of which joined console.trace on the line.
9 console.assert (value [, message] [ , ...])
For determining whether a variable or expression is true, it took two parameters, the first parameter is the expression and the second argument is a string. Only when the first argument is false, the output will be the second argument, it would not have any results.
console.log (): print to the standard output stream and end with a newline character.

console.log accepts several parameters, if there is only one parameter, the output string of this parameter. If there are multiple arguments, places like the C language printf () command output format.

The first parameter is a string, without parameters, only print a newline.

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

Operating results as follows:

Hello world 
byvoid%diovyb 
byvoid1991iovyb 
  • console.error (): with console.log () uses the same, but the output to the standard error stream.
  • console.trace (): error stream to the standard output the current call stack.
console.trace();

Operating results as follows:

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)

Examples

Create a file main.js, code as follows:

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

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

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

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

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

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

process

process is a global variable that attribute global object.

It is used to describe the current state of the object Node.js process, it provides a simple interface to the operating system. Typically you write native command line program, and ultimately, to deal with it. The following will introduce some of the most commonly used method of process members object.

No. Events & Description
1 exit
Fires when the process is ready to quit.
2 beforeExit
This event is triggered when the node empty event loop, and no other arrangements. Generally, when there is no process to arrange exit node, but 'beforeExit' listeners can be called asynchronously, so that node will continue.
3 uncaughtException
When an exception bubbling back to the event loop, trigger this event. If you add a monitor to the exception, the default action (print a stack trace and exit) will not occur.
4 Signal is triggered when the event<br> when the process receives a signal. See a list of signal standard POSIX signal names such as SIGINT, SIGUSR1 and so on.

Examples

Create a file main.js, code as follows:

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

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

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

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

Exit status codes

Exit status codes are as follows:

Status Code Title & Description
1 Uncaught Fatal Exception
There uncaught exception, and it has not been processed or domain uncaughtException handler.
2 Unused
Retention
3 Internal JavaScript Parse Error
JavaScript source code parsing error caused when starting Node process. Very rarely, only when there will be in the development of Node.
4 Internal JavaScript Evaluation Failure
JavaScript source Node startup process, when evaluating the function returns failure. Very rarely, only when there will be in the development of Node.
5 Fatal Error
V8 in unrecoverable error fatal. Usually print to stderr, content: FATAL ERROR
6 Non-function Internal Exception Handler
Uncaught exception, exception handler inside somehow set on-function, and can not be called.
7 Internal Exception Handler Run-Time Failure
Uncaught exception, and the exception handler to handle their own throws an exception. For example, if process.on ( 'uncaughtException') or domain.on ( 'error') throws an exception.
8 Unused
Retention
9 Invalid Argument
It may be unknown to the parameters or parameter to no value.
10 Internal JavaScript Run-Time Failure
JavaScript source code is thrown when starting Node process errors, very rare, only when there will be in the development of Node.
12 Invalid Debug Argument
--debug Parameter set and / or --debug-brk, but chose the wrong port.
> 128 Signal Exits
If Node receives a fatal signal, such as SIGKILL or SIGHUP, then the exit code is 128 plus the signal code. This is the standard Unix practice, high code on exit signals.

Process attributes

Process provides many useful properties, ease of interaction that we can better control the system:

Number. Property & Description
1 stdout
Standard output stream.
2 stderr
Standard error stream.
3 stdin
Standard input stream.
4 argv
argv property returns an array of various parameters on the command-line script execution when the composition. Its first members are always node, the second member is the script file name, and the remaining members are the parameters of the script file.
5 execPath
Returns the absolute path of the current script execution Node binaries.
6 execArgv
Returns an array member is under the command-line script is executed between the Node executable script file command line parameters.
7 env
Returns an object, the members of the current shell environment variable
8 exitCode
Exit code for the process, if the process gifted by process.exit () exit, without specifying an exit code.
9 version
Node version, such v0.10.18.
10 versions
A property that contains the node versions and dependencies.
11 config
Object that contains the current node is used to compile the executable file javascript configuration options. It is the same run ./configure script generated "config.gypi" file.
12 pid
The current process number.
13 title
Process name, the default is "node", you can customize the value.
14 arch
The current CPU architecture: 'arm', 'ia32' or 'x64'.
15 platform
Run the program where the platform 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
16 mainModule
require.main alternative methods. Different point, if the main module is changed at runtime, require.main may continue to return to the old module. It is believed that both refer to the same module.

Examples

Create a file main.js, code 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);

Executive 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 a lot of useful methods to facilitate better control of our interactive system:

No. Method & description
1 abort ()
This will cause the node abort trigger event. It will exit node and generate a core file.
2 chdir (directory)
Change the current working directory of the process, if the operation fails throw.
3 cwd ()
Returns the working directory of the current process
4 exit ([code])
The end of the process with the specified code. If omitted, it will use the code 0.
5 getgid ()
Get process group identification (see getgid (2)). When the group was acquired digital id, not name.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
6 setgid (id)
Setting group identification process (See setgid (2)). You can receive a digital ID or group name. If you specify a group name will resolve to block waiting for a digital ID.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
7 getuid ()
Get user identification process (see getuid (2)). This is a numeric user id, not the user name.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
8 setuid (id)
User ID setting process (see setuid (2)). Receiving a digital ID or string name. If you specify a group name will resolve to block waiting for a digital ID.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
9 getgroups ()
Return process group iD array. POSIX system does not guarantee that there is, but there is node.js guaranteed.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
10 setgroups (groups)
Set process group ID. It is authorized to operate, all you need to have root privileges, or have CAP_SETGID capacity.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
11 initgroups (user, extra_group)
Read / etc / group, and initializes the group access list, all group members are located. It is authorized to operate, all you need to have root privileges, or have CAP_SETGID capacity.
Note: This function can be used (for example, non-Windows and Android) only on POSIX platforms.
12 kill (pid [, signal])
Sends a signal to the process. Pid is the process id, and the signal is the string describing the signal transmitted. Signal names are strings like 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
13 memoryUsage ()
It returns an object that describes the process used by the Node memory status bytes.
14 nextTick (callback)
Once the end of the current event loop, call back functions.
15 umask ([mask])
Set or read process file mask. Child processes inherit the mask from the parent process. If the mask argument is valid, it returns the old mask. Otherwise, it returns the current mask.
16 uptime ()
Returns the number of seconds Node is already running.
17 hrtime ()
Time resolution of the current process, in the form [seconds, nanoseconds] array. It is with respect to any past event. This value has nothing to do with the date, therefore not affect the clock drift. The main purpose is through the precise time interval, to measure the performance of the program.
Before you can pass the result to the current process.hrtime (), it will return to the time difference between the two, for the reference and measurement time interval.

Examples

Create a file main.js, code as follows:

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

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

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

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

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