How to Read a File in Node.js: Simple Guide with Examples
In Node.js, you can read a file using the
fs module's readFile or readFileSync methods. readFile reads files asynchronously without blocking the program, while readFileSync reads files synchronously and blocks execution until done.Syntax
The fs module provides two main ways to read files:
- Asynchronous:
fs.readFile(path, options, callback)reads the file without stopping other code. Thecallbackruns when reading finishes. - Synchronous:
fs.readFileSync(path, options)reads the file and waits until done before moving on.
path is the file location, options can specify encoding like 'utf8' to get text instead of raw data.
javascript
import { readFile, readFileSync } from 'fs'; // Asynchronous syntax readFile(path, options, (err, data) => { // handle error or use data }); // Synchronous syntax const data = readFileSync(path, options);
Example
This example shows how to read a text file asynchronously and print its contents. It also shows the synchronous way for comparison.
javascript
import { readFile, readFileSync } from 'fs'; const filePath = './example.txt'; // Asynchronous read readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading file asynchronously:', err); return; } console.log('Async file content:', data); }); // Synchronous read try { const dataSync = readFileSync(filePath, 'utf8'); console.log('Sync file content:', dataSync); } catch (err) { console.error('Error reading file synchronously:', err); }
Output
Async file content: Hello, this is example text.
Sync file content: Hello, this is example text.
Common Pitfalls
Common mistakes when reading files in Node.js include:
- Forgetting to specify encoding, which returns raw buffer data instead of readable text.
- Using synchronous reading in performance-critical or server code, which blocks the event loop and slows down the app.
- Not handling errors in the callback or try-catch, which can crash the program.
Always handle errors and prefer asynchronous reading for better performance.
javascript
import { readFile } from 'fs'; // Wrong: no encoding, data is buffer readFile('./example.txt', (err, data) => { if (err) throw err; console.log(data); // prints <Buffer ...> }); // Right: specify encoding to get string readFile('./example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); // prints file content as text });
Quick Reference
Summary tips for reading files in Node.js:
- Use
fs.readFilefor non-blocking file reads. - Use
fs.readFileSynconly for scripts or startup code. - Always specify encoding like
'utf8'to get text. - Handle errors properly to avoid crashes.
Key Takeaways
Use fs.readFile for asynchronous, non-blocking file reading in Node.js.
Specify encoding like 'utf8' to get readable text instead of raw data buffers.
Handle errors in callbacks or try-catch blocks to prevent crashes.
Avoid fs.readFileSync in server code to keep your app responsive.
The fs module is built-in, so no extra installation is needed.