I am currently learning Node.js at the Zuri Training and I have purposed to write about what I learn. This article simply shows you how to read and write files using NodeJS.
Writing and reading files is an important basic skill for a programmer as you will need to read from a file or write to a file in your day-to-day activities. Node.js makes it much easier by using one of its modules known as the fs module. The fs module allows us to manipulate files and perform CRUD(Create, Read, Update, Delete) operations when handling files on your computer. The file system is commonly used to:
Create files
Read files
Update files
Delete files
Rename files
We don't need to install the fs module as it comes with Node installed. We simply have to import it, so that we can use it to manipulate files as shown below.
const fs = require('fs');
Since we have imported the module and got it stored in an object called fs, we shall use it to access all its methods. The fs module has both asynchronous and synchronous ways to handle files.
Synchronous: Blocks the execution of code until the file operation is complete which means that the program won't continue until it is complete.
Asynchronous: Does not block the execution of code. It simply invokes a callback function once the file operation is complete.
In this article, we shall look at the asynchronous version of handling files.
Creating or writing to files.
To create files, we use the writeFile() method that writes data to a file. The method takes in some parameters which include: the path to the file to write in, the content we are going to write, and a call back function to help us handle errors.
Example
We shall create a new file and call it write.js and then write the following code.
const fs = require('fs');
fs.writeFile('file.txt', 'Hello World', (err) => {
/* if there is an error throw error */
if (err) throw err;
console.log('file created successfully');
});
Run the code by typing node write.js in the terminal and then open up file.txt in your code editor, you will see the new contents of the file.
Reading from files.
To read files, we use the readFile() method that reads the entire contents of the file asynchronously. The method takes two arguments: the file path and the callback function that will be called with the file data. The callback function is passed with two arguments: err and data where the err object contains information about errors and data which is the contents of the file.
Example
const fs = require('fs');
const http = require('http');
http.createServer((req, res) => {
fs.readFile('text.html', (err, data) => {
if (err) throw err;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(4000);
Appending to or updating a file
To append a file, we can use the appendFile() and writeFile() methods.
The appendFile() method appends data at the end of the file and if the file doesn't exist, it's created. Therefore, the appendFile() method can also be used for the creation of files.
const fs = require('fs');
fs.appendFile('file.txt', '\nLearning NodeJS: File System', (err) => {
if (err) throw err;
console.log('file updated!');
});
The writeFile() method will override the content and replace the specified file with new content.
const fs = require('fs');
fs.readFile('file.txt', '\nLearning NodeJS: File System', (err) => {
if (err) throw err;
console.log('file replaced!');
});
Deleting files
To delete files, we use the unlink() method of the fs module. The method deletes the specified file and like the other methods, it takes in two arguments; file path(file to be deleted) and a callback function.
const fs = require('fs');
fs.unlink('myNewFile.txt', (err) => {
if (err) throw err;
console.log('file deleted');
});
Renaming files
To rename files, we use the rename() method that renames the specified file. It takes three arguments; a name of the old file path, a name of the new file path, and a callback function as seen below.
const fs = require('fs');
fs.rename('file.js', 'newFile.js', (err) => {
if (err) throw err;
console.log('file renamed successfully');
});
For more information about the NodeJS file system and its methods, read the documentation here.
Conclusion.
That is how we basically modify files using the NodeJS File System. Until next time, thanks for reading!!