Reading files synchronously means your program waits until the file is fully read before moving on. This is simple and useful when you need the file data right away.
Reading files synchronously in Node.js
const fs = require('fs');
const data = fs.readFileSync(path, options);path is the file path as a string or a Buffer or URL.
options can specify encoding like 'utf8' to get a string instead of a buffer.
const fs = require('fs'); const content = fs.readFileSync('file.txt', 'utf8');
const fs = require('fs'); const buffer = fs.readFileSync('image.png');
const fs = require('fs'); const content = fs.readFileSync('data.json', { encoding: 'utf8' });
This program reads 'example.txt' synchronously as a UTF-8 string. It prints the file content if successful, or an error message if the file is missing or unreadable.
const fs = require('fs'); try { const data = fs.readFileSync('example.txt', 'utf8'); console.log('File content:'); console.log(data); } catch (err) { console.error('Error reading file:', err.message); }
Reading files synchronously blocks the whole program until done, so avoid it in servers or apps needing high responsiveness.
Always handle errors with try-catch to avoid crashes if the file doesn't exist or can't be read.
For large files or performance-critical apps, prefer asynchronous reading methods.
Reading files synchronously is simple and waits for the file to be fully read before continuing.
Use it for small files or scripts where blocking is not a problem.
Remember to handle errors and consider async methods for better performance.