Node.js的是“异步的console.log? [英] is node.js' console.log asynchronous?

查看:108
本文介绍了Node.js的是“异步的console.log?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在node.js中的console.log /调试/警告/错误 - 异步?我的意思是将JavaScript的code执行停止,直到东西是显示在屏幕上还是会在后期打印?

Are console.log/debug/warn/error in node.js asynchrounous? I mean will javascript code execution halt till the stuff is printed on screen or will it print at a later stage?

另外,我想知道,如果有可能,如果语句崩溃节点后立即向的console.log不显示任何内容。

Also, I am interested in knowing if it is possible for a console.log to NOT display anything if the statement immediately after it crashes node.

推荐答案

更新:与节点0.6这篇文章开始已经过时,因为stdout是的同步的现在

Update: Starting with Node 0.6 this post is obsolete, since stdout is synchronous now.

那么让我们来看看的console.log 实际上做。

Well let's see what console.log actually does.

所有它的控制台模块的一部分首先:

First of all it's part of the console module:

exports.log = function() {
  process.stdout.write(format.apply(this, arguments) + '\n');
};

所以,它只是做了一些格式和写入 process.stdout ,没什么异步至今。

process.stdout 是一个getter的在其上延迟初始化启动的定义,我加入了一些注释来解释的东西:

process.stdout is a getter defined on startup which is lazily initialized, I've added some comments to explain things:

.... code here...
process.__defineGetter__('stdout', function() {
  if (stdout) return stdout;                            // only initialize it once 

  /// many requires here ...

  if (binding.isatty(fd)) {                             // a terminal? great!
    stdout = new tty.WriteStream(fd);
  } else if (binding.isStdoutBlocking()) {              // a file?
    stdout = new fs.WriteStream(null, {fd: fd});
  } else {
    stdout = new net.Stream(fd);                        // a stream? 
                                                        // For example: node foo.js > out.txt
    stdout.readable = false;
  }

  return stdout;
});

在一个TTY和UNIX的情况下,我们这里,这最终生命从插座继承。因此,所有节点bascially确实是推到插座上的数据,然后是终端其余的工作。

In case of a TTY and UNIX we end up here, this thing inherits from socket. So all that node bascially does is to push the data on to the socket, then the terminal takes care of the rest.

让我们来测试一下吧!

var data = '111111111111111111111111111111111111111111111111111';
for(var i = 0, l = 12; i < l; i++) {
    data += data; // warning! gets very large, very quick
}

var start = Date.now();
console.log(data);
console.log('wrote %d bytes in %dms', data.length, Date.now() - start);

结果

....a lot of ones....1111111111111111
wrote 208896 bytes in 17ms

real    0m0.969s
user    0m0.068s
sys  0m0.012s

的终端需要约1秒至打印出插座的内容,但节点只需要17毫秒的数据推送到该终端。

The terminal needs around 1 seconds to print out the sockets content, but node only needs 17 milliseconds to push the data to the terminal.

这同样适用于流情况下,以及文件的情况下得到处理异步

The same goes for the stream case, and also the file case gets handle asynchronous.

所以 Node.js的也是如此,以自己的无阻塞的承诺。

So yes Node.js holds true to its non-blocking promises.

这篇关于Node.js的是“异步的console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆