The fs module in Node.js supports both synchronous and asynchronous file operations.
1. Asynchronous Operations
Definition: These operations do not block the execution of the program. The program may continue running other code while the file operation is being carried out. The result is handled by a callback function, a Promise, or async/await after the operation is finished.
Example: fs.readFile is an asynchronous method.
const fs = require('fs');fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data);});console.log('This will print first!');
Output:
"This will print first!" (immediate)
File content (later, when read operation completes)
2. Synchronous Operations
Definition: These operations block the execution of the program until the task completes. This means no further code runs until the file operation is finished.
Example: fs.readFileSync is a synchronous method.
const fs = require('fs');const data = fs.readFileSync('example.txt', 'utf8');console.log(data);console.log('This will print after the file is read.');
Output:
File content
"This will print after the file is read." (after the read operation)