Blocking functions

Accessing external resources

Blocking or non-blocking operating model is relevant when dealing with input/output operations. Writing to a resource or reading from a resource are considered I/O operations. The targets for such operations can be anything from files to network sockets to screen to keyboard. Any resource that is not accessible instantly at the machine instruction level but involves waiting instead requires I/O communication.

Computer memory, on the other hand, can be addressed instantly and does not require waiting. Accessing memory is therefore not considered an I/O operation. In fact, the random-access memory (RAM) name originates from its ability to access any location in the same amount of time irrespective of its physical location.

Blocking

Operating system labels processes with a state based on how ready they are to be put on CPU.
Blocking term originates from the operating system process model. A multitasking operating system labels each process with a state depending on how ready they are to be put on the CPU for execution. A process is labeled blocked if it is not ready for execution but is instead waiting for an I/O event to take place. I/O events indicate progress or completion in an I/O operation, for example "resource available" or "write complete".

Performing a blocking system call causes the process to enter the blocked state. Control is let back to the process only after the I/O event that is being waited upon occurs.

In Node.js the filesystem module contains fs.xSync methods that provide blocking versions of the filesystem operations.

1

2

3

4

var fs = require('fs');

var contents = fs.readFileSync('file.txt', 'utf8');

// this line is not reached until the read results are in

console.log(contents);

Using blocking version, the call will not return until the I/O is completed. When the call returns, it provides the results for the operation as return value. The results are returned synchronously.

A blocking call causes results to be returned synchronously.