Dino Geek, try to help you

How to use FS module in Node.js?


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.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use