关于进程 I/O 的注意事项


【A note on process I/O】

process.stdoutprocess.stderr 在重要方面与其他 Node.js 流不同:

  1. 它们分别由 console.log()console.error() 内部使用。

  2. 写入操作可能是同步的,这取决于流所连接的对象以及系统是 Windows 还是 POSIX:

    • 文件:在 Windows 和 POSIX 上为 同步

    • TTY(终端):在 Windows 上为 异步,在 POSIX 上为 同步

    • 管道(和套接字):在 Windows 上为 同步,在 POSIX 上为 异步

这些行为部分是出于历史原因,因为改变它们会造成向后不兼容,但也有一些用户对此有所期待。

【These behaviors are partly for historical reasons, as changing them would create backward incompatibility, but they are also expected by some users.】

同步写入可以避免诸如使用 console.log()console.error() 输出时意外交错,或如果在异步写入完成前调用 process.exit() 导致输出根本未写入的问题。更多信息请参见 process.exit()

【Synchronous writes avoid problems such as output written with console.log() or console.error() being unexpectedly interleaved, or not written at all if process.exit() is called before an asynchronous write completes. See process.exit() for more information.】

警告: 同步写操作会阻塞事件循环,直到写入完成。对于文件输出,这可能几乎是瞬时完成,但在系统负载较高、接收端未读取的管道,或使用慢速终端或文件系统的情况下,事件循环可能会被频繁且长时间阻塞,从而产生严重的性能负面影响。在写入交互式终端会话时,这可能不是问题,但在对进程输出流进行生产环境日志记录时,应特别注意这一点。

Warning: Synchronous writes block the event loop until the write has completed. This can be near instantaneous in the case of output to a file, but under high system load, pipes that are not being read at the receiving end, or with slow terminals or file systems, it's possible for the event loop to be blocked often enough and long enough to have severe negative performance impacts. This may not be a problem when writing to an interactive terminal session, but consider this particularly careful when doing production logging to the process output streams.】

要检查一个流是否连接到 文字电话 上下文,请检查 isTTY 属性。

【To check if a stream is connected to a TTY context, check the isTTY property.】

例如:

【For instance:】

$ node -p "Boolean(process.stdin.isTTY)"
true
$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
false
$ node -p "Boolean(process.stdout.isTTY)"
true
$ node -p "Boolean(process.stdout.isTTY)" | cat
false 

有关更多信息,请参阅 文字电话 文档。

【See the TTY documentation for more information.】