Wondering how to use fs Module in Node.js to manage files?
The file system module or fs module supports interacting with files synchronously and asynchronously.
Some common features of the fs module include reading, writing, updating, deleting, and renaming files.
At Bobcares, we often use the fs module in Node.js as a part of our Server Management Services.
Today let’s see the steps our Support Engineers follow while using the fs module in Node.js to work with files.
How to manage files using fs Module in Node.js
Node.js helps to manipulate files programmatically with the built-in fs module. In this article, we will see how to read, write and delete files using the fs module in Node.js.
We need to ensure that we have Node.js installed on the local machine to access the fs module and JavaScript to work with files as prerequisites.
The steps our Support Techs follow are given below:
1. Reading Files with readFile()
We will write a program to read files in Node.js.
Steps to follow are given below:
1. First we will create a folder to store the code.
$ mkdir node-files
$ cd node-files
2. Then we will create the file greetings.txt with the following command:
z<code$ echo "hello, hola, bonjour, hallo" > greetings.txt
3. Now, we can create and open readFile.js with any text editor.
$ nano readFile.js
4. And type the following code:
const fs = require('fs').promises;
Here we are using the fs module to interact with the filesystem and we will be importing the .promises part of the module.
Once the module is imported, we can create an asynchronous function to read the file.
5. For this first we will create a new function readFile() that accepts one argument, a string called filePath.
Enter the following code:
const fs = require('fs').promises; async function readFile(filePath) { try { const data = await fs.readFile(filePath); console.log(data.toString()); } catch (error) { console.error(`Got an error trying to read the file: ${error.message}`); } }
The fs.readFile() returns a buffer object by default. A buffer object can store any kind of file type.
6. Finally, we can call the function on the greetings.txt file with the following code:
const fs = require('fs').promises; async function readFile(filePath) { try { const data = await fs.readFile(filePath); console.log(data.toString()); } catch (error) { console.error(`Got an error trying to read the file: ${error.message}`); } } readFile('greetings.txt');
7. Now save and exit the editor.
We can confirm that the program works fine with the following:
$ node readFile.js
The following output can be seen:
hello, hola, bonjour, hallo
2. Writing Files with writeFile()
We will write files with the writeFile() function of the fs module.
1. First, we need to open a new file in any text editor:
$ nano writeFile.js
2. We will begin with importing the fs module:
const fs = require('fs').promises;
Here also we will use async/await syntax to create two functions.
3. Enter the following code to create the CSV function first:
const fs = require('fs').promises; async function openFile() { try { const csvHeaders = 'name,quantity,price' await fs.writeFile('groceries.csv', csvHeaders); } catch (error) { console.error(`Got an error trying to write to a file: ${error.message}`); } }
4. Next, we will create a new function to add items to the grocery list by adding the following function in the text editor:
const fs = require('fs').promises; async function openFile() { try { const csvHeaders = 'name,quantity,price' await fs.writeFile('groceries.csv', csvHeaders); } catch (error) { console.error(`Got an error trying to write to a file: ${error.message}`); } } async function addGroceryItem(name, quantity, price) { try { const csvLine = `\n${name},${quantity},${price}` await fs.writeFile('groceries.csv', csvLine, { flag: 'a' }); } catch (error) { console.error(`Got an error trying to write to a file: ${error.message}`); } }
5. For completing the script, we will use the following functions:
... async function addGroceryItem(name, quantity, price) { try { const csvLine = `\n${name},${quantity},${price}` await fs.writeFile('groceries.csv', csvLine, { flag: 'a' }); } catch (error) { console.error(`Got an error trying to write to a file: ${error.message}`); } } (async function () { await openFile(); await addGroceryItem('bun', 12, 5.50); await addGroceryItem('apple', 10, 14); })();
6. Finally save and exit the text editor.
7. We can run the code with the node command:
$ node writeFile.js
No output will be available after running the above command. However, we will have a new file that exists in our current directory.
8. We can use the cat command to display the contents of the file groceries.csv:
$ cat groceries.csv
The following output can be seen:
name,quantity,price bun,12,5.5 apple,10,14
3. Deleting Files with unlink()
Next, we will delete files with the unlink() function in the fs module.
We will write a Node.js script to delete the groceries.csv file that we created earlier using the following steps:
1. First, create a new file for this Node.js module:
$ nano deleteFile.js
2. We will add below code that creates an asynchronous deleteFile() function
const fs = require('fs').promises; async function deleteFile(filePath) { try { await fs.unlink(filePath); console.log(`Deleted ${filePath}`); } catch (error) { console.error(`Got an error trying to delete the file: ${error.message}`); } } deleteFile('groceries.csv');
The unlink() function removes the file permanently from the filesystem.
3. Finally save and exit the text editor.
4. We can run the code with the node command:
$ node deleteFile.js
The following output can be seen:
Deleted groceries.csv
[Need assistance to use fs module? We are happy to help you!]
Conclusion
To conclude, we saw the various functions that can be performed with fs Module in Node.js such as reading, writing, and deleting files. Also, we saw the steps our Support Engineers follow to implement this.
0 Comments