Reputation: 459
Quite confused discovered (on nodejs example, not sure about other langs yet) lately that all three stdio streams are a full duplexes (i.e. both readable and writable).
I'm not sure whether the first my question should be the why. Yet it might be helpful to solve the puzzle as well.
From the other side what really stands behind all the other directions. E.g. what supposed to mean writing into the stdin
itself.
But the main question is on top of all these is about the following consequences.
I have this as a basis:
const {Transform} = require('stream')
// just an util to visualize the source
const streamLogger = (name) => new Transform({
transform(chunk, encoding, callback) {
callback(null, `--------${name} ${chunk}`);
},
})
Starting with a simple
process.stdin.pipe(streamLogger('stdin')).pipe(process.stderr)
node index.js
>>>abc
<<<--------stdin abc
>>>def
<<<--------stdin def
Quite as expected, so far
process.stdin.pipe(streamLogger('stdin')).pipe(process.stderr)
process.stdout.pipe(streamLogger('stdout')).pipe(process.stderr)
node index.js
>>>abc
<<<--------stdout abc
>>>def
<<<--------stdout def
So why the stdin
is just switched to stdout
regardless stdin
was even piped (subscribed) in the first place?
And even more interesting
process.stdin.pipe(streamLogger('stdin')).pipe(process.stderr)
process.stdout.pipe(streamLogger('stdout')).pipe(process.stderr)
process.stdin.write('hello\n')
node index.js
<<<hello
>>>abc
<<<--------stdout abc
>>>def
<<<--------stdout def
Why is hello
even printed bypassing the logger at all?
So what's really going on over here?
PS: oh - just discovered even more strange.
Once changed the pipes order (stdout
goes first)
process.stdout.pipe(streamLogger('stdout')).pipe(process.stderr)
process.stdin.pipe(streamLogger('stdin')).pipe(process.stderr)
It just competes for the data like
node index.js
>>>abc
<<<--------stdin abc
>>>def
<<<--------stdout def
>>>ghi
<<<--------stdin ghi
>>>jkl
<<<--------stdout jkl
Please help to make sense of this.
Thanks
Upvotes: 0
Views: 38