I've read the docs about the Console object and A note on process I/O, but can't figure out if the following would result in a synchronous or asynchronous operations:
const out = fs.createWriteStream('./out.log') const logger = new Console(out) logger.log('foo')
I'm curious about how this acts, especially on a *Nix system. But I wouldn't expect this to act differently on a Windows. The reason I am asking is because I had built a logger which leveraged the Console object, but I don't want the logger to be blocking when writing logs to files while in production.
2 Answers
Answers 1
tldr;
According to Node's official documentation, what you are doing here is synchronous because you are using files.
Writes may be synchronous depending on the what the stream is connected to and whether the system is Windows or Unix:
- Files: synchronous on Windows and Linux
- TTYs (Terminals): asynchronous on Windows, synchronous on Unix
- Pipes (and sockets): synchronous on Windows, asynchronous on Unix
Warning: I strongly recommending not to use these synchronous actions on production services, because synchronous writes block the event loop until the write has completed. This can be a serious drawback when doing production logging.
Reference: Node.js Official Documentations / A note on process I/O
Answers 2
It will be asynchronous.
Internally Console
class maintains a callback _stdoutErrorHandler
to trigger after the write operation is completed and check for errors. We can test for asynchronicity using it.
const fs = require('fs'); const { Console } = require('console'); const str = new Array(100).fill('').map(() => 'o'.repeat(1000 * 1000)).join(''); const out = fs.createWriteStream('./o.txt'); const logger = new Console(out); logger._stdoutErrorHandler = () => { console.log('written');}; logger.log(str); console.log('hey');
You'll see that 'hey' get printed before 'written'.
The note on process I/O applies to process.stdin
and process.stdout
which are special streams. When they point to files, as in the following:
$ node someCode.js > file.txt
... in Unix the write operation in Unix will be synchronous. This is handled in lines here. In such cases, process.stdout
stream will be connected to a file and not the usual unix file descriptor fd1
.
0 comments:
Post a Comment