×


Managing files with fs Module in Node js

Are you trying to figure out how to use fs Module in Node.js to manage files?

This guide will help you.


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.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to use fs module in Node.js.

In this context, we shall look into how to use 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. Here, you will learn 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 to 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:

i. First we will create a folder to store the code.

$ mkdir node-files
$ cd node-files

ii. Then we will create the file greetings.txt with the following command:

z<code$ echo "hello, hola, bonjour, hallo" > greetings.txt

iii. Now, we can create and open readFile.js with any text editor.

$ nano readFile.js

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


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


vi. 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');

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

i. First, we need to open a new file in any text editor:

$ nano writeFile.js

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


iii. 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}`);
}
}

iv. 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}`);
}
}

v. 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);
})();

vi. Finally save and exit the text editor.

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

viii. 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:

i. First, create a new file for this Node.js module:

$ nano deleteFile.js

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


iii. Finally save and exit the text editor.


iv. We can run the code with the node command:

$ node deleteFile.js

The following output can be seen:

Deleted groceries.csv

[Need urgent assistance to use fs module? We are happy to help you! ]


Conclusion

This article will guide you on various functions that can be performed with fs #Module in Node.js such as reading, writing, and deleting files.

#Node . js includes fs module to access physical file system. The #fs module is responsible for all the asynchronous or synchronous file I/O operations.

To use FS in node JS:

The Node. js file system #module allows you to work with the file system on your #computer. To include the File System module, use the require() method: var fs = require('fs'):

1. Read files.

2. Create files.

3. Update files.

4. Delete files.

5. Rename files.