How to Read File Synchronously in Node.js with fs.readFileSync
In Node.js, you can read a file synchronously using the
fs.readFileSync method from the built-in fs module. This method blocks the program until the file is fully read and returns its content as a string or buffer.Syntax
The fs.readFileSync method reads a file synchronously and returns its content. It takes two main arguments:
- path: The file path as a string.
- options (optional): An object or string specifying the encoding (like 'utf8') or other flags.
If encoding is specified, the method returns a string; otherwise, it returns a buffer.
javascript
const fs = require('fs'); const data = fs.readFileSync(path, options);
Example
This example reads a text file named example.txt synchronously and prints its content to the console. It uses UTF-8 encoding to get a readable string.
javascript
const fs = require('fs'); try { const data = fs.readFileSync('example.txt', 'utf8'); console.log('File content:', data); } catch (err) { console.error('Error reading file:', err.message); }
Output
File content: Hello, this is example text.
Common Pitfalls
Reading files synchronously blocks the entire program until the file is read, which can slow down your app if the file is large or the operation is frequent.
Also, forgetting to handle errors can crash your program if the file does not exist or is inaccessible.
Always use try...catch to handle errors when using fs.readFileSync.
javascript
const fs = require('fs'); // Wrong: no error handling const data = fs.readFileSync('missing.txt', 'utf8'); console.log(data); // Right: with error handling try { const data = fs.readFileSync('missing.txt', 'utf8'); console.log(data); } catch (err) { console.error('File not found or cannot be read:', err.message); }
Quick Reference
Remember these key points when using fs.readFileSync:
- Use
utf8encoding to get a string output. - Wrap calls in
try...catchto handle errors safely. - Use synchronous reading only for small files or scripts where blocking is acceptable.
Key Takeaways
Use fs.readFileSync(path, encoding) to read files synchronously in Node.js.
Always handle errors with try...catch to avoid crashes.
Synchronous reading blocks the program; avoid it in performance-critical code.
Specify encoding like 'utf8' to get string output instead of a buffer.
Use synchronous reading mainly for small files or simple scripts.