Reading files with promises lets you get file content without blocking your program. It helps keep your app fast and smooth.
0
0
Reading files with promises (fs.promises) in Node.js
Introduction
You want to read a text file and then do something with its content.
You need to read multiple files one after another without freezing your app.
You want to handle errors easily when reading files.
You are building a server that reads configuration files on start.
You want to use modern JavaScript with async/await for cleaner code.
Syntax
Node.js
import { promises as fs } from 'fs'; async function readFileExample() { try { const data = await fs.readFile('filename.txt', 'utf8'); console.log(data); } catch (error) { console.error('Error reading file:', error); } }
Use fs.readFile from fs.promises to get a promise that resolves with file content.
Always use try/catch or .catch() to handle errors when reading files.
Examples
Using
.then() and .catch() to handle the promise from reading a file.Node.js
import { promises as fs } from 'fs'; fs.readFile('example.txt', 'utf8') .then(data => console.log(data)) .catch(err => console.error(err));
Using
async/await for cleaner, easier-to-read code.Node.js
import { promises as fs } from 'fs'; async function read() { const content = await fs.readFile('example.txt', 'utf8'); console.log(content); } read();
Handling errors gracefully when the file does not exist.
Node.js
import { promises as fs } from 'fs'; async function readFile() { try { const data = await fs.readFile('missing.txt', 'utf8'); console.log(data); } catch (error) { console.error('File not found or error:', error.message); } } readFile();
Sample Program
This program reads the file greeting.txt and prints its content. If the file is missing or unreadable, it shows an error message.
Node.js
import { promises as fs } from 'fs'; async function showFileContent() { try { const content = await fs.readFile('greeting.txt', 'utf8'); console.log('File content:'); console.log(content); } catch (error) { console.error('Failed to read file:', error.message); } } showFileContent();
OutputSuccess
Important Notes
Always specify the encoding like 'utf8' to get a string instead of a buffer.
Promises let you write asynchronous code that looks like normal, step-by-step code.
Use Node.js DevTools or console logs to check if your file path is correct.
Summary
Use fs.promises.readFile to read files asynchronously with promises.
Handle errors with try/catch or .catch() to avoid crashes.
Use async/await for clean and readable asynchronous code.