Node.js内置的常用模块
global
Node.js交互环境
> global.console
Console {
log: [Function: bound ],
info: [Function: bound ],
warn: [Function: bound ],
error: [Function: bound ],
dir: [Function: bound ],
time: [Function: bound ],
timeEnd: [Function: bound ],
trace: [Function: bound trace],
assert: [Function: bound ],
Console: [Function: Console] }
process
process也是Node.js提供的一个对象,它代表当前Node.js进程。
> process === global.process;
true
> process.version;
'v5.2.0'
> process.platform;
'darwin'
> process.arch;
'x64'
> process.cwd(); //返回当前工作目录
'/Users/michael'
> process.chdir('/private/tmp'); // 切换当前工作目录
undefined
> process.cwd();
'/private/tmp'
JavaScript程序是由事件驱动执行的单线程模型,Node.js也不例外。Node.js不断执行响应事件的JavaScript函数,直到没有任何响应事件的函数可以执行时,Node.js就退出了。
如果我们想要在下一次事件响应中执行代码,可以调用process.nextTick():
// test.js
// process.nextTick()将在下一轮事件循环中调用:
process.nextTick(function () {
console.log('nextTick callback!');
});
console.log('nextTick was set!');
nextTick was set!
nextTick callback!
在程序即将退出时执行某个回调函数:
// 程序即将退出时的回调函数:
process.on('exit', function (code) {
console.log('about to exit with code: ' + code);
});
判断JavaScript执行环境
if (typeof(window) === 'undefined') {
console.log('node.js');
} else {
console.log('browser');
}
console.log('current js file:'+__filename);//d:\workspace\js\test\app.js
console.log('current js dir: '+__dirname);//d:\workspace\js\test
process.name='Sample Nodejs';
console.log('arguments: '+JSON.stringify(process.argv));//["C:\\Program Files\\nodejs\\node.exe","d:\\workspace\\js\\test\\app.js"]
console.log('cwd: '+process.cwd());//d:\workspace\js
var d='/private/tmp';
if(process.platform==='win32'){
d='C:\\Windows\\System32';
}
process.chdir(d);
console.log('cmd '+process.cwd());//C:\Windows\System32
// process.nextTick()将在下一轮事件循环中调用:
process.nextTick(function(){
console.log('nextTick callback!');
});
console.log('nextTick was set!');
//nextTick was set!
//nextTick callback!
// 程序即将退出时的回调函数:
process.on('exit',function(code){
console.log('about to exit with code: '+code);
//about to exit with code: 0
});