Probably a basic question for those familiar with the topic. Consider the following toy program:
const fs = require('fs');
process.stdout.on('data', (chunk) => {
fs.writeFileSync('myfile.txt', chunk, 'utf-8'); // just an example
});
process.stdout.write('xyz');
If I run this code just as it is, I get the following error:
errno: -4053,
code: 'ENOTCONN',
syscall: 'read'
I already do not understand why that happens. But it gets even stranger:
When I run the code with a console.log() before it, no error is thrown anymore! However, the listener I defined for the data event seems not to be executed in that case, as no text file is created.
Can someone explain to me why this happens and what I can do get the expected result (here write to myfile.txt)?
The first error you see is caused by trying to connect to stdout to get its data. You haven't written anything to stdout, so it's not initialized, so you can't connect to it! ENOTCONN means exactly that: Error: Not Connected (to the stdout socket).
Now, for the second error. console.log() is an alias for process.stdout.write('\n'). So when you run the code with a console.log() before it, you've now initialized stdout, so you can connect to it and no ENOTCONN error will be thrown. But you're waiting for input to come from the console from stdout. Input doesn't come from stdout; it comes from stdin.
To fix this, you need to:
stdin before connecting to it, using process.stdin.resume().data from stdin rather than stdout, using process.stdin.on(...).stdin, using process.exit(0).const fs = require('fs')
process.stdin.resume()
process.stdin.on('data', (chunk) => {
fs.writeFileSync('mytestfile.txt', chunk, 'utf-8')
// Uncomment the following line if you want to write
// something to the console to indicate success
// process.stdout.write("Got your input!")
process.exit(0)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With