The FS module is a built-in module in Node.js for interacting with the file system. Each I/O method in the FS module has a synchronous and asynchronous form. For example, ‘readFile()’ and ‘writeFile()’ are common asynchronous methods, while ‘readFileSync()’ and ‘writeFileSync()’ are their synchronous counterparts.
Here’s how to use the FS module:
Step 1: Include the FS module
First, you need to include the FS module in your file:
```
var fs = require(‘fs’);
```
Step 2: Read a file
To read a file, you can use the ‘readFile()’ method. The first parameter is the filename and the second is a callback function:
```
fs.readFile(‘myFile.txt’, ‘utf8’, function(err, data){
if (err) throw err;
console.log(data);
});
```
Note: ‘utf8’ is the file encoding. It’s optional and the default encoding is ‘utf8’.
Step 3: Write to a file
To write to a file, you can use the ‘writeFile()’ method:
```
fs.writeFile(‘myNewFile.txt’, ‘Content to write’, function(err){
if (err) throw err;
console.log(‘File is created!’);
});
```
You can also use ‘appendFile()’ method to append data to an existing file:
```
fs.appendFile(‘myFile.txt’, ‘Content to append’, function(err){
if (err) throw err;
console.log(‘Content appended!’);
});
```
Step 4: Delete a file
To delete a file, you can use the ‘unlink()’ method:
```
fs.unlink(‘myFile.txt’, function(err){
if (err) throw err;
console.log(‘File deleted!’);
});
```
Step 5: Create a directory
To create a new directory, you can use the ‘mkdir()’ method:
```
fs.mkdir(‘myDirectory’, function(err){
if (err) throw err;
console.log(‘Directory created!’);
});
```
Step 6: Delete a directory
To delete a directory, you can use the ‘rmdir()’ method:
```
fs.rmdir(‘myDirectory’, function(err){
if (err) throw err;
console.log(‘Directory deleted!’);
});
```
These examples used asynchronous methods. If you use the synchronous versions, you don’t provide a callback function. Instead, they will return the result directly or throw an error.