Using the File System Module in Node Js

Using the File System Module in Node Js

When working with Node JS, most times, we often would have to create, delete, write on and even update files. A file can be seen as a document that contains some form of information, either text-based or even code. The files you create can also be in various extensions, like .txt, .css, .js, .html, etc

In Node JS, File System Module allows us to work with files by providing unique functions for creating and updating the content of a file.

N/B: To be able to use the fs module, you must have Node JS installed on your computer

I wrote about how you can get started with Node JS and you can read it here

To get started using the fs module, create a new directory on your code editor, for instance, VS Code and navigate there. A directory is simply a location where we store files. See the code below;

$ mkdir myFiles
$ cd myFiles

Now create a new .js file called Index.js. This file is where we will make use of the functions available in the fs module.

In the index.js file you can 'require' the fs module.

To 'require' is like making the fs module available for our use. Without requiring the module, we can't use it. We require it at the very top of our page. See the code below;

const fs = require("fs");

Yay! That simple, the fs is now available for our use.

CREATING DIRECTORIES USING FS MODULE

This new directory will contain the file we create and update using the fs module. Again, a directory is simply a location where we store files. You can imagine it as a folder.

To create a directory, we first check if it already exists using the 'fs.existsSync', the exclamation before it can be referred to as a negation syntax. So, that line reads, if the 'newFolder' does not exist...

The 'fs.mkdir' is something we have used already, it creates a new folder 'IF' the directory does not exist, and takes a callback function that checks for any errors while printing "created successfully" to the console if no errors.

See the code below;

if (!fs.existsSync("./newFolder")) {
     fs.mkdir("./newFolder", (err, data) => {
       if (err) {
       console.log(err);
      }
     console.log("created successfully");
     });

Another thing we can do is remove or delete an existing directory using the 'fs.rmdir'. Notice, this time there's no exclamation as we are checking if the directory does exist.

See the code below;

if(fs.existsSync("./newFolder")){
    fs.rmdir("./assets", (err, data) => {
       if (err) {
        console.log(err);
       }
    console.log("removed successfully");
   });

CREATING FILES USING FS MODULE

To create a new file similar to the index.js we created earlier, but this time using the fs module, we use the 'fs.writeFile' syntax.

It takes three parameters, first, the file path/directory you want to store the newly created file with the name of the file, in our case which is "blog.txt", the second parameter is the content you want in the file, which in our case is 'Hello cosmosDuck, this is your new file' and finally, a callback function that checks for any errors while printing "successful" to the console if no errors.

N/B: .txt is a text-based file. The 'fs.writefile' is used to both create a new file as well as update an existing file.

See the code below;

 fs.writeFile('./newFolder/blog.txt', 'Hello cosmosDuck, this is your new                         file', (err, data) => {
     if (err) {
      console.log(err)
  } console.log('successful')

READING FILES USING FS MODULE

Now we have created our file, we can as well read the content we wrote in it using the "fs.readFile" syntax. This takes two parameters, which are the file path and callback function.

Notice, we use the "toString()" when printing our content to the console. This is to ensure the information we get comes in a human-readable format.

See the code below;

 fs.readFile('./newFolder/blog.txt', (err, data) => {
     if (err) {
      console.log(err)
  } console.log(data.toString())

 })

DELETING FILES USING FS MODULE

Similar to creating directories, we first need to check if the file we intend to delete does exist before proceeding to delete it.

To delete, we use the "fs.unlink" syntax.

See the code below;

if (fs.existsSync('./newFolder/blog.txt')) {
    fs.unlink('./newFolder/blog.txt', (err, data) => {
        if (err) {
            console.log(err)
        } console.log('deleted successfully')
    })
}

And this brings us to a wrap.

They're other too numerous to mention functions available in the 'fs module', you can check the node js documentation to get a hang of it. Click here.

Stay tune!