Posts

Showing posts from March, 2019

Node Js - Blocking and Non-Blocking Concept.

Look at these two blocks of code and find the difference. var fs = require ( "fs" ); var data = fs . readFileSync ( 'input.txt' ); console . log ( data . toString ()); console . log ( "Program Ended" ); var fs = require ( "fs" ); fs . readFile ( 'input.txt' , function ( err , data ) { if ( err ) return console . error ( err ); console . log ( data . toString ()); }); console . log ( "Program Ended" ); These two examples explain the concept of blocking and non-blocking calls. The first example shows that the program blocks until it reads the file and then only it proceeds to end the program. The second example shows that the program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file. Thus, a blocking program executes very much in sequence. From the programming point of view, it i

Node.js for I/O bound, Not for CPU bound.

Image
What do these terms ' I/O bound ' and  ' CPU bound '  mean? I/O bound This is the case for typical Node.js web server application. Majority of the time is spent waiting for network, filesystem and perhaps database I/O to complete. Increasing hard disk speed or network connection improves the overall performance. In its most basic form Node.js is best suited for this type of computing. All I/O in Node.js is non-blocking and it allows other requests to be served while waiting for a particular read or write to complete. CPU bound An example of CPU bound application would be a service that calculates SHA-1 checksums. Majority of the time is spent crunching the hash - doing large amount of bitwise xors and shifts for the input string. This kind of application leads to trouble in Node.js. If the application spends too much time performing CPU intensive task all other requests are being held up. Node.js runs a single threaded event loop to concurrently advan