An asynchronous function in Node.js is a function that runs independently of the main program flow and can be used to execute a task without blocking the main program. Asynchronous functions are generally used for I/O operations such as reading from a file or making an API call.
Example:
const fs = require(‘fs’);
// Asynchronous function to read a file
const readFile = (filePath, callback) => {
fs.readFile(filePath, (err, data) => {
if (err) {
callback(err);
} else {
callback(null, data);
}
});
};
// Call the asynchronous function
readFile(‘/path/to/file.txt’, (err, data) => {
if (err) {
console.error(err);
} else {
console.log(data);
}
});