Skip to content
Advertisement

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?

Advertisement

Answer

Everything in node.js is basically “atomic”. That’s because node.js is single threaded – no code can ever be interrupted.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement