Last week, we learned how to asynchronously check if a file exists in Node.js. I mentioned that you shouldn't use this technique before reading/writing files, and that I'd show you what to do instead. That's what we're gonna do today!
Reading files
The fs.readFile()
method lets you asynchronously read the entire contents of a file. It accepts up to three arguments:
- The path to the file.
- An object literal of options or a string to specify the encoding.
- A callback function with
error
anddata
parameters.
In the following examples, I'm using the string 'utf8'
as the encoding, which saves me from having to parse the data as a Buffer.
Callback API
import { readFile } from 'fs';
readFile('./package.json', 'utf8', (error, data) => {
if (error) {
throw error;
} else {
console.log(data);
}
});
Promises API
The fsPromises.readFile()
method returns a promise that fulfills with the contents of the file.
import { readFile } from 'fs/promises';
readFile('./package.json', 'utf8')
.then(console.log)
.catch(console.error);
Writing files
The fs.writeFile()
method lets you asynchronously write data to a file, replacing the file if it already exists. It accepts up to four arguments:
- The path to the file.
- The data to write to the file.
- An object literal of options or a string to specify the encoding.
- A callback function with an
error
parameter.
In the following examples, I'm again using the string 'utf8'
as the encoding.
Callback API
import { writeFile } from 'fs';
const file = 'hello_world.txt';
const data = 'Hello, World!';
writeFile(file, data, 'utf8', error => {
if (error) {
throw error;
} else {
console.log(`Successfully wrote '${data}' to ${file}.`);
}
});
Promises API
The fsPromises.writeFile()
method returns a promise that fulfills with undefined
upon success. This means we don't need to specify a parameter for our callback to the then()
method.
import { writeFile } from 'fs/promises';
const file = 'hello_world.txt';
const data = 'Hello, World!';
writeFile(file, data, 'utf8')
.then(() => console.log(`Successfully wrote '${data}' to ${file}.`))
.catch(console.error);
What if I don't want to overwrite the file?
The writeFile()
method overwrites the file if it already exists. Next week, we'll learn how to append data to a file using the appendFile()
method.