The fs.readFile()
method in Node.js is part of the fs
(File System) module and is used to asynchronously read the contents of a file.
Here is a basic syntax:
const fs = require('fs');
fs.readFile(path, options, (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
// The file content is in the `data` argument
console.log('File content:', data.toString()); // converting buffer to string
});
Parameters:
- path (string | Buffer | URL): The path to the file you want to read.
- options (optional):
encoding
(string | null): The character encoding to use (e.g.,'utf8'
). If not provided, it will return aBuffer
.flag
(string): A string flag to specify the behavior (e.g.,'r'
for reading).
- callback: A callback function that takes two arguments:
err
: An error object (if an error occurs).data
: The content of the file (as aBuffer
or a string depending on the encoding).
Example with Encoding:
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
Important Points:
- The method is asynchronous, so it does not block the execution of the program while the file is being read.
- The callback is executed once the file reading operation is complete, passing the file content (or error if something went wrong).
- If no encoding is specified, the result will be a
Buffer
, which you can convert to a string (using.toString()
).