Home >Web Front-end >JS Tutorial >Node.js global objects

Node.js global objects

黄舟
黄舟Original
2017-01-17 15:58:091303browse

Learning points:

- __filename

- __dirname

- setTimeout(cb, ms)

- setInterval(cb, ms)

- clearTimeout(t)

- console

- process

Node.js global object

Global object in Node.js global, all global variables are attributes of the global object. In Node.js, we can directly access the global attributes 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.

When we define a global variable, this variable will also become a property of the global object global.

__filename represents the file name of the currently executing script

[code]console.log("文件所在的路径:" + __filename);

__dirname represents the directory where the currently executing script is located

[code]console.log("文件所在的目录:" + __dirname);

setTimeout(cb, ms) delayer object

setInterval(cb, ms) timer object

clearTimeout(t) clear delayer

Case: main.js
[code]console.log("文件所在的路径:" + __filename);
console.log("文件所在的目录:" + __dirname);
var printHello = function () {
    console.log("Hello, World");
}
// 1s后调用函数
var t = setTimeout(printHello, 1000);
// 清除延时器
clearTimeout(t);

Node.js global objects

##console object


Case: console.js

[code]console.info("程序开始执行:");
var counter = 10;
console.log("计数:%d", counter);
console.time("获取数据");
console.timeEnd("获取数据");
console.info("程序执行完毕");
// 当进程准备退出时触发
process.on('exit', function (code) {
    // 以下代码永远不会执行
    setTimeout(function () {
        console.log("该代码不会执行");
    }, 0);
    console.log("退出代码:", code);
});
console.log("程序执行结束");

Node.js global objects

Case 3: process.js

[code]// 输出到终端
process.stdout.write("Hello World!" + "\n");
// 通过参数读取
// argv 属性返回一个数组,由命令行执行脚本时的各个参数组成。
// 它的第一个成员总是node,第二个成员是脚本文件名,其余成员是脚本文件的参数。
process.argv.forEach(function (val, index, array) {
    console.log(index + ": " + val);
    // 0: D:\nodeJS安装包\node.exe
    // 1: E:\node\全局对象\process.js
});
// 获取执行路局
// D:\nodeJS安装包\node.exe
console.log(process.execPath);
// 平台信息
// wind32
console.log(process.platform);
// 输出当前目录
console.log("当前目录:" + process.cwd());
// 输出当前版本
console.log('当前版本:' + process.version);
// 输出内存使用情况
console.log(process.memoryUsage());

Node.js global objects

The above is the content of the Node.js global object. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Node.js flexible routingNext article:Node.js flexible routing