DEV Community

Santosh Vaza
Santosh Vaza

Posted on

Whether NodeJS is right platform for your WebAPIs ?

Javascript is the language for NodeJS platform which is native to all front-end developers, Hence it enables many developers to write server side code without going through additional OR with minimal learning curve. Many developers who have just entered the software development world (A warm welcome to them :) ) find it easy to learn and code in javascript. However NodeJS is not the last bar in server side development.

I personally like the simplicity of NodeJS, I am a big fan of it's package management system and managing project dependencies. These simplicity comes with a cost. Its not bad but it can be, if one is not aware of below important NodeJS concepts.

Javascript runtime

Single Threaded

The javascript code whether in browser/nodejs executes on one single main thread called as Event loop. So it means that while the javascript code is in execution (For example : A long running while loop) no other parts of your application will be able to run at that time, Not even callbacks like event handlers or ajax callbacks etc. Every such callbacks ariving that time will be queued to internal Message Queue and will be processed one after another based on their arrival. If the main thread is idle and a message arrives in a message queue (basically a notification to execute a callback), v8 will execute it on main thread with right context. This is how a callback function remembers the enclosing lexical scope..... closures.

Non Blocking asynchronous I/O

A callback function is provided while instructing NodeJS to perform I/O operation (Reading/Writing a file, Socket operations). The actual I/O operation performs on the background thread called as worker pool, while it happens, V8 further continues to execute your remaining part of function. If there is no javascript code to further execute and I/O is still in process then we say that main thread blocked.
While a thread is blocked working on behalf of one client, it cannot handle requests from any other clients.

CONCLUSION

So this means that in a NodeJS web server scenario your web application runs on a single thread and if a request takes time to execute then this will result in very poor performance because it will make other requests to wait until current request execution is finished. It becomes very important that you shouldn't do too much work for any client in any single callback or task. Every request should be completed very fast. This is the reason why NodeJs can scale well, but it also means that you are responsible for ensuring fair scheduling.

If the code that is written on NodeJS platform is going to take more time or CPU then one should think, Whether NodeJS is right platform for your WebAPIs?

Top comments (0)