Dino Geek, try to help you

How to read and write files in Node.js?


Reading and writing files in Node.js can be accomplished using the built-in ‘fs’ module. Here is how you can do it:

1. Reading files

To read a file content in Node.js, you call fs.readFile(file, callback) function.

Example:

```
const fs = require(‘fs’);

fs.readFile(‘./example.txt’, ‘utf8’ , (err, data) => { if (err) { console.error(err) return } console.log(data)
})
```

In the example above, ‘./example.txt’ is the file to be read, and the ‘utf8’ parameter signifies the encoding type of the file. The callback function is called after the file has been read.

1. Writing files

To write to a file, you use fs.writeFile(file, data, callback) function.

Example:

```
const fs = require(‘fs’)

fs.writeFile(‘./example.txt’, ‘This is some text’, err => { if (err) { console.error(err) return } //file written successfully
})
```

In the example above, ‘./example.txt’ is the file to be written to, ‘This is some text’ is the data to write to the file. The callback is called after the write operation ends. If the operation was successful, it will receive no arguments, otherwise it will receive an error argument.

NOTE: If the file doesn’t exist at the given path, `fs.writeFile` will create the file for you, while `fs.readFile` will return an error if the file doesn’t exist. Be aware that `fs.writeFile` will replace content if the file already exists, to add content at the end of the file use `fs.appendFile`.


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