process是全局对象,在任何地方都可以访问,而且它是EventEmitter的一个实例(关于EventEmitter后面会提到)。
process对象对一些标准的输入输出流进行了封装,如stdin(标准输入)、stdout(标准输出)和stderr(标准错误输出)。其中,stdin和stdout支持异步操作,前者可读,后者可写。stderr是一个同步可阻塞流。
使用stdin和stdout来读取和写入数据:
process.stdin.setEncoding(‘utf-8‘); process.stdin.on(‘readable‘, function(){ var chunk = process.stdin.read(); if(chunk !== null){ process.stdout.write(‘data: ‘+ chunk); } }); process.stdin.on(‘end‘, function(){ process.stdout.write(‘end‘); });
作为流,process.stdin可以在旧模式下使用。为了兼容node v0.10以前的版本。在旧模式喜爱使用stdin必须调用process.stdin.resume()。注意如果调用了process.stdin.resume() stdin将转为旧模式。
process.stdin.resume(); process.stdin.on(‘data‘, function(chunk){ process.stdout.write(‘data: ‘ + chunk); });
上述两者的结果都是:
[email protected]:~/nodejs-workspace/03process$ node stdin.js adfasfas data: adfasfas asdfasf data: asdfasf daddddddddddddddddddddd data: daddddddddddddddddddddd[email protected]:~/nodejs-workspace/03process$ #按Ctrl + D时显式end
process总包含许多属性和方法可以返回当前环境信息,可以查看API:
> process.version #Node版本信息 ‘v0.12.1‘ > process.execPath #返回当前Node应用程序的执行路径 ‘/usr/local/bin/node‘ > process.platform #服务器平台信息 ‘linux‘ > process.memoryUsage() #内存使用情况 { rss: 18534400, heapTotal: 11803648, heapUsed: 6462296 } > process.pid #当前程序的进程号 4058 > process.arch #架构信息 ‘x64‘ > process.uptime() #运行时间 1782.254 >
下面简单说一下nextTick()方法,详细请看文末参考:
process.nextTick()将一个回调函数挂载到Node程序的时间循环机制中,在下一个事件循环发生时调用该函数。
示例1:
[email protected]:~/nodejs-workspace/03process$ cat nextTick.js console.log(‘start‘); process.nextTick(function() { console.log(‘nextTick callback‘); }); console.log(‘scheduled‘); // Output: // start // scheduled // nextTick callback
上述程序的运行结果为:
[email protected]:~/nodejs-workspace/03process$ node nextTick.js start scheduled nextTick callback
示例2:
[email protected]:~/nodejs-workspace/03process$ cat nextTick02.js function foo(options){ console.log(‘foo function‘); } process.nextTick(foo); console.error(‘bar‘);
上述程序的运行结果为:你可以发现bar比‘foo function‘提前打印了出来.也就是说我们已经将调用foo()推迟到下一个事件循环中.
[email protected]:~/nodejs-workspace/03process$ node nextTick02.js bar foo function
同样我们采用setTimeout()同样可以达到上述效果。
[email protected]:~/nodejs-workspace/03process$ cat setTimeoutCompareNextTick02.js function foo(options){ console.log(‘foo function‘); } setTimeout(foo, 0); console.error(‘bar‘);
结果同上:
[email protected]:~/nodejs-workspace/03process$ node setTimeoutCompareNextTick02.js bar foo function
但是process.nextTick()相对setTimeout()来说是高效的.
More precisely, process.nextTick()
defers the function until a completely new stack. You can call as many functions as you want in the current stack. The function that called nextTick has to return, as well as its parent, all the way up to the root of the stack. Then when the event loop is looking for a new event to execute, your nextTick
‘ed function will be there in the event queue and execute on a whole new stack.
参考:http://howtonode.org/understanding-process-next-tick