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`.