Node.js › Event Loop & Non-blocking IO
What is the difference between synchronous and asynchronous versions of the same core Node.js API, using fs.readFile vs fs.readFileSync as an example, and when is the synchronous version actually appropriate?
IntermediateAnswer
The synchronous version blocks the entire event loop until the operation completes, returning its result directly rather than via a callback or promise -- generally discouraged in a server handling concurrent requests, but genuinely appropriate in specific contexts like a one-off CLI script's startup sequence (reading a config file before anything else happens, where blocking briefly at startup causes no harm since there's nothing else concurrently happening yet) or simple, single-purpose scripts with no concurrency concerns at all.
// Appropriate use of the synchronous version: reading config once at startup,
// before the server starts accepting any concurrent requests
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
app.listen(config.port); // only starts accepting requests after config is loadedReal-world example A CLI tool that runs once, processes a file, and exits uses fs.readFileSync() throughout without concern, since there's no concurrent request-handling happening that a brief synchronous block could interfere with, unlike in a running web server.