Sobes.tech
Junior

Which operations and functions are synchronous in the code?

sobes.tech AI

Answer from AI

Synchronous operations block the thread until they complete.

Examples of synchronous operations in Node.js:

  • File system operations ending with Sync:
    const fs = require('fs');
    
    // Synchronous file read
    const data = fs.readFileSync('file.txt', 'utf8');
    
  • CPU-intensive blocking functions in modules that do not use asynchronous APIs, e.g., complex mathematical calculations in a loop.
  • Certain native modules (C++) operations if not implemented asynchronously.
  • Operations that are inherently blocking at the OS level, e.g., waiting for console input.

Most built-in Node.js functions that deal with network operations, file system, databases, etc., have asynchronous counterparts to avoid blocking the main thread. Synchronous versions are typically used only in command-line utilities or during initialization where blocking is acceptable.