1.Reading a File
Synchronous Method
const data = fs.readFileSync(‘example.txt’, ‘utf8’);
console.log(data);
- Blocks execution until the file is read.
Asynchronous Method
fs.readFile(‘example.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
- Non-blocking, preferred in real applications.
2. Writing to a File
Synchronous Method
fs.writeFileSync(‘example.txt’, ‘Hello, World!’);
console.log(‘File written successfully’);
Asynchronous Method
fs.writeFile(‘example.txt’, ‘Hello, World!’, (err) => {
if (err) {
console.error(err);
return;
}
console.log(‘File written successfully’);
});
3. Appending Data to a File
Synchronous Method
fs.appendFileSync(‘example.txt’, ‘\nAppended text.’);
Asynchronous Method
fs.appendFile(‘example.txt’, ‘\nAppended text.’, (err) => {
if (err) throw err;
console.log(‘Data appended’);
});
4. Deleting a File
Synchronous Method
fs.unlinkSync(‘example.txt’);
Asynchronous Method
fs.unlink(‘example.txt’, (err) => {
if (err) throw err;
console.log(‘File deleted’);
});
5. Renaming a File
Synchronous Method
fs.renameSync(‘oldname.txt’, ‘newname.txt’);
Asynchronous Method
fs.rename(‘oldname.txt’, ‘newname.txt’, (err) => {
if (err) throw err;
console.log(‘File renamed’);
});
6. Working with Directories
Creating a Directory
fs.mkdirSync(‘myDir’); // Synchronous
fs.mkdir(‘myDir’, (err) => {
if (err) throw err;
console.log(‘Directory created’);
});
Deleting a Directory
fs.rmdirSync(‘myDir’); // Synchronous
fs.rmdir(‘myDir’, (err) => {
if (err) throw err;
console.log(‘Directory deleted’);
});