File System Operation in NodeJS with Examples

Last updated Oct 19, 2021

In this article, the file system operation in NodeJS will be covered. Many operations that related with file can be done using built-in package from NodeJS called fs.

 

How do I Read a File in NodeJS

To read a specified file, use the readFile() function. In this example, the file called myfile.txt is read then the content from this file is shown in the console.

// import fs package
const fs = require("fs");

// read a file
fs.readFile("myfile.txt", "utf-8", (err, data) => {
  // if error occurred, throw the error
  if (err) {
    throw err;
  }

  // show the content from specified file.
  console.log(data);
});

Output

this is sample file.

Based on the code above, the readFile() function is used to read a file called myfile.txt. The readFile() function takes three parameters including path to the specific file, the encoding type then the callback. The encoding type that is used is utf-8.

 

How do i Create a File in Nodejs?

There are many functions that can be used to create a file including writeFile(), appendFile() and open(). In this example, the writeFile() is used to create a new file.

// import fs package
const fs = require("fs");

// create a new file called cool.txt
fs.writeFile("cool.txt", "hello", (err) => {
  if (err) {
    throw err;
  }
  console.log("new file is created!");
});

Output

new file is created!

 

Based on the code above, the new file called cool.txt is created. If the file exists, the file is replaced with new file that already created. If the file is not exist then the new file with specified content is created.

In this example, the appendFile() is used to create a new file.

// import fs package
const fs = require("fs");

// create a new file called other.txt
fs.appendFile("other.txt", "my content", (err) => {
  if (err) {
    throw err;
  }
  console.log("file is created!");
});

Output

file is created!

Based on the code above, the new file called other.txt is created. If the file is exists, the specified content is added into the specified file. If the file is not exists, the new file is created.

In this example, the open() function is used to create an empty file.

// import fs package
const fs = require("fs");

// create a new file called test.txt
fs.open("test.txt", "w", (err, file) => {
  if (err) {
    throw err;
  }
  console.log("file is created!");
});

Output

file is created!

Based on the code above, the new file called test.txt is created.

 

How do i Update a File in NodeJs

There are two functions that can be used to update certain file including writeFile() and appendFile(). In this example, the appendFile() is used to update the content from specific file called cool.txt.

// import fs package
const fs = require("fs");

// update a file content in cool.txt
fs.appendFile("cool.txt", "updated", (err) => {
  if (err) {
    throw err;
  }
  console.log("file is updated");
});

Output

file is updated

Based on the code above, the file content is updated. The appendFile() is used to append new content so the previous content is not replaced directly.

To replace an entire content inside file, the writeFile() function can be used. This is the example of using writeFile().

// import fs package
const fs = require("fs");

// update a file content in other.txt
fs.writeFile("other.txt", "all content is replaced", (err) => {
  if (err) {
    throw err;
  }
  console.log("file content is replaced!");
});

Output

file content is replaced!

 

How do I Delete a File?

To delete a specific file, use unlink() function. In this example, the unlink() function is used to delete a file called cool.txt.

// import fs package
const fs = require("fs");

// delete a file called cool.txt
fs.unlink("cool.txt", (err) => {
  if (err) {
    throw err;
  }
  console.log("file is deleted!");
});

Output

file is deleted!

Based on the code above, the file is deleted.

 

Node JS File Example

In this example, the content from sample.txt file is retrieved then the word that is palindrome is saved inside another file called palindrome.txt.

File content in sample.txt.

the radar was found in specified level
// create a function
// to check if a certain word is palindrome
const isPalindrome = (word) => {
  let letters = word.split("");
  let result = "";

  for (let index = letters.length - 1; index >= 0; index--) {
    result += letters[index];
  }

  if (result === word) {
    return true;
  }
  return false;
};

// import fs package
const fs = require("fs");

// create an array to store words from file
let words = [];

// create an array to store palindrome words
let palindromes = [];

// read file
const contents = fs.readFileSync("sample.txt", "utf-8");

// split a file content by space
words = contents.split(" ");

// check for each word
// if certain word is palindrome
words.forEach((word) => {
  if (isPalindrome(word)) {
    palindromes.push(word);
  }
});

// store all palindrome words in palindrome.txt file
palindromes.forEach((palindrome) => {
  fs.appendFile("palindrome.txt", palindrome + "\n", (err) => {
    if (err) {
      throw err;
    }
    console.log("content is appended!");
  });
});

Output

content is appended!
content is appended!

File content in palindrome.txt.

radar
level

I hope this article is helpful to learn file system operations in NodeJS.

Conclusion: In this Node JS tutorial we covered how to create a file and update a file, delete a file.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

693 Views