Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is console.log atomic?

The print statement in Python is not thread-safe. Is it safe to use console.log in Node.js concurrently?

If so, then is it also interleave-safe? That is, if multiple (even hundreds) of callbacks write to the console, can I be sure that the output won't be clobbered or interleaved?

Looking at the source code, it seems that Node.js queues concurrent attempts to write to a stream (here). On the other hand, console.log's substitution flags come from printf(3). If console.log wraps around printf, then that can interleave output on POSIX machines (as shown here).

Please show me where the async ._write(chunk, encoding, cb) is implemented inside Node.js in your response to this question.

EDIT: If it is fine to write to a stream concurrently, then why does this npm package exist?

like image 801
Coder Avatar asked Jun 27 '26 16:06

Coder


2 Answers

Everything in node.js is basically "atomic". That's because node.js is single threaded - no code can ever be interrupted.

like image 173
slebetman Avatar answered Jun 29 '26 06:06

slebetman


The events loop of nodejs is single thread, but all the async calls of nodejs are multi-threaded, it use libuv under the hood, libuv is library that use multi threads.

link: https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c

like image 24
Adam va Avatar answered Jun 29 '26 05:06

Adam va



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!