0
0
Node.jsframework~5 mins

Reading files synchronously in Node.js

Choose your learning style9 modes available
Introduction

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.

When you need to read a small configuration file before starting your app.
When writing a quick script that processes a file and exits.
When you want to keep code simple and don't mind waiting for the file read to finish.
When debugging or testing and want straightforward file access.
When the file size is small and blocking the program briefly is acceptable.
Syntax
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.

Examples
Reads 'file.txt' as a string using UTF-8 encoding.
Node.js
const fs = require('fs');
const content = fs.readFileSync('file.txt', 'utf8');
Reads 'image.png' as a raw buffer (binary data).
Node.js
const fs = require('fs');
const buffer = fs.readFileSync('image.png');
Reads 'data.json' as a string using an options object for encoding.
Node.js
const fs = require('fs');
const content = fs.readFileSync('data.json', { encoding: 'utf8' });
Sample Program

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.

Node.js
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);
}
OutputSuccess
Important Notes

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.

Summary

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.