Can node.js code result in race conditions?

Jatin picture Jatin · Jan 29, 2014 · Viewed 18.8k times · Source

From what I read, race conditions occur when different threads try to change a shared variable, which can result in a value that's not possible with any serial order of execution of those threads.

But code in node.js runs in a single thread, so, does that mean code written in node.js is free of race conditions?

Answer

Hector Correa picture Hector Correa · Jan 29, 2014

Yes. Node.js can run into race conditions as soon as you start sharing resources.

I mistakenly also thought you couldn't get race conditions in Node.js because it's single threaded nature, but as soon as you use a shared resource outside of node (e.g. a file from the file system) you can get into a race condition. I posted an example of this issue in this question when I was trying to understand this: node.js readfile woes

What is different in Node.js from other environments is that you have a single thread of JavaScript execution so there is only one JavaScript instance running your code (as oppossed to a threaded environment in which there are many threads executing your app code at the same time.)