关于进程 I/O 的注意事项
¥A note on process I/O
process.stdout
和 process.stderr
在重要方面与其他 Node.js 流不同:
¥process.stdout
and process.stderr
differ from other Node.js streams in
important ways:
-
它们分别由
console.log()
和console.error()
内部使用。¥They are used internally by
console.log()
andconsole.error()
, respectively. -
写入可能是同步的,具体取决于流连接到什么以及系统是 Windows 还是 POSIX:
¥Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX:
-
档案:在 Windows 和 POSIX 上同步
¥Files: synchronous on Windows and POSIX
-
TTY(终端):在 Windows 上异步,在 POSIX 上同步
¥TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
-
管道(和套接字):在 Windows 上同步,在 POSIX 上异步
¥Pipes (and sockets): synchronous on Windows, asynchronous on 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.
要检查流是否连接到 TTY 上下文,请检查 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
有关更多信息,请参阅 TTY 文档。
¥See the TTY documentation for more information.