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);
[code]console.log("文件所在的路径:" + __filename); console.log("文件所在的目录:" + __dirname); var printHello = function () { console.log("Hello, World"); } // 1s后调用函数 var t = setTimeout(printHello, 1000); // 清除延时器 clearTimeout(t);
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("程序执行结束");
[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());