Blocking (Synchronous) code of Node.js for reading files
In blocking code, the processor will execute the instructions sequentially which means the next instruction has to wait until the current instruction is executed. So progressively, the waiting time is high in the buffer pool, at the same time the computers are working efficiently.For exampleconst fs = require(‘fs’);console.log(‘start’);const data = fs.readFileSync(‘./file.txt’, ‘utf-8’); // blocks here until file is readconsole.log(‘data: ‘, data.trim());console.log(‘end’);The function “readFileSync” is used to read the file in Synchronous mode or blocking I/O which means that when executing the function “readFileSync”, it will read the file synchronously and in the meantime, the program will wait until the file is completely read. Due to this, the program execution time is relatively high.startdata: Hello World!
end
Non-Blocking (Asynchronous) code of Node.js for reading files
In non-blocking code, the processor will execute the code in parallel, which means the execution is carried out continuously. It works independently from the outside of the program workflow.For Exampleconst fs = require(‘fs’);console.log(‘start’);fs.readFile(‘./file.txt’, ‘utf-8’, (err, data) => {if (err) throw err;console.log(‘data: ‘, data.trim());});console. log(‘end’);In the asynchronous mode of execution, initially, it prints ‘start’ and then when reading the file using ‘readFile()’ function the next statement is executed without waiting for the completion of the ‘readFile()’ function. Once the file has been read it will execute its callback function to finalize the statement.startenddata: Hello World!
What you should consider when making a decision?
- The asynchronous mode of execution is faster than the synchronous model because it won’t wait for the completion of instruction execution.
- Compared to the synchronous, there is a chance to occur error in the asynchronous.
- Working with the asynchronous model is trickier than the synchronous model.
- Asynchronous allows the user to manage the CPU more efficiently than the synchronous model.
Conclusion
To run this shortly, asynchronous has its fair share of benefits and synchronous has its fair share. We hope this helps you understand better what is what and which can you benefit the most from.Our services:
- Staffing: Contract, contract-to-hire, direct hire, remote global hiring, SOW projects, and managed services.
- Remote hiring: Hire full-time IT professionals from our India-based talent network.
- Custom software development: Web/Mobile Development, UI/UX Design, QA & Automation, API Integration, DevOps, and Product Development.
Our products:
- ZenBasket: A customizable ecommerce platform.
- Zenyo payroll: Automated payroll processing for India.
- Zenyo workforce: Streamlined HR and productivity tools.