在下面的例子里有一个compute(),我们希望这个函数尽可能持续的执行,来进行一些运算密集的任务。
但与此同时,我们还希望系统不要被这个函数堵塞住,还需要能响应处理别的事件。这个应用模式就像一个单线程的web服务server。在这里我们就可以使用process.nextTick()来交叉执行compute()和正常的事件响应。
var http = require(‘http’);
function compute() {
// performs complicated calculations continuously
// …
process.nextTick(compute);
}
http.createServer(function(req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘Hello World’);
}).listen(5000, ‘127.0.0.1’);
compute();
在这种模式下,我们不需要递归的调用compute(),我们只需要在事件循环中使用process.nextTick()定义compute()在下一个时间点执行即可。
在这个过程中,如果有新的http请求进来,事件循环机制会先处理新的请求,然后再调用compute()。
反之,如果你把compute()放在一个递归调用里,那系统就会一直阻塞在compute()里,无法处理新的http请求了。你可以自己试试。
当然,我们无法通过process.nextTick()来获得多CPU下并行执行的真正好处,这只是模拟同一个应用在CPU上分段执行而已。
(2),Console
console {Object} Used to print to stdout and stderr.See the stdio section.
控制台 {对象} 用于打印到标准输出和错误输出。看如下测试:
console.log(“Hello Bigbear !”) ;
for(var i in console){
console.log(i+” “+console[i]) ;
}
会得到以下输出结果:
var log = function () {
process.stdout.write(format.apply(this, arguments) + ‘n’);
}
var info = function () {
process.stdout.write(format.apply(this, arguments) + ‘n’);
}
var warn = function () {
writeError(format.apply(this, arguments) + ‘n’);
}
var error = function () {
writeError(format.apply(this, arguments) + ‘n’);
}
var dir = function (object) {
var util = require(‘util’);
process.stdout.write(util.inspect(object) + ‘n’);
}
var time = function (label) {
times[label] = Date.now();
}
var timeEnd = function (label) {
var duration = Date.now() – times[label];
exports.log(‘undefined: NaNms’, label, duration);
}
var trace = function (label) {
// TODO probably can to do this better with V8’s debug object once that is









