📅  最后修改于: 2023-12-03 15:15:12.053000             🧑  作者: Mango
The fs.readFile
method is a built-in function of the Node.js file system module that is used to read the contents of a file asynchronously. This method allows a file to be read without blocking the code execution of the rest of the application.
fs.readFile(path[, options], callback)
The fs.readFile
method accepts three parameters:
path
: The path to the file that needs to be read. This can be a string or a URL object.options
: An optional argument that can be used to specify encoding, flags or mode.callback
: A callback function that is called with two arguments: error
and data
. The error
argument is null
if there is no error and data
argument contains the file content.const fs = require('fs')
fs.readFile('example.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
In this example, the fs.readFile
method is used to read the contents of the file example.txt
. The utf-8
encoding option is specified, and a callback function is used to handle the results of the method call.
The fs.readFile
method is a powerful and easy-to-use function for reading files asynchronously in Node.js. It allows for efficient file-reading without blocking the execution of the rest of the application.