Skip to content
/ Stream/stdio
12/2/2023
1.2m
AI 摘要

本文介绍 Node.js 中 stdio 的结构和用法,包括 stdinstdoutstderr 的原型链关系,并通过示例展示如何使用 process.stdin 接收和发送数据。重点在于 stdio 的继承结构和实际应用。

stdio

包括 stdinstdoutstderr.

结构

__proto__
instance
prototype
__proto__
instance
prototype
__proto__
__proto__
__proto__
__proto__
__proto__
__proto__
__proto__
prototype
instance
process.stdio
fs.ReadableStream.prototype
fs.ReadableStream
process.stdout
process.stderr
fs.WriteableStream.prototype
fs.WriteableStream
net.Socket.prototype
stream.Duplex.prototype
stream.Readable.prototype
stream.Stream.prototype
events.EventEmitter's instance
events.EventEmitter.prototype
events.EventEmitter
stdio/stdout/stderr 的原型链

stdio in process

We can access stdio in Nodejs process.

process.stdin means input of process. So if we try to log process.stdin:

// index.ts
process.stdin.on('data', chunk => {
    console.log('recive stdin chunk: ' chunk)
})

The data output in the terminal will be same as our input:

hello   # handle input
recive stdin chunk: hello 
world   # handle input
recive stdin chunk: world

Also, we can write chunk by write method:

process.stdin.setEncoding('utf-8').on('data', data => {
    console.log('get stdin', data)
})

let count = 0
setInterval(() => {
    process.stdin.write(count.toString())
    count++
}, 1000)

Released under the MIT License.