Using Node.js File System Module

Node.js File System Module helps you to work with files on your computer or server.You can read, edit, write, create or rename files.

To use file system you need to import them i.e var fs=require(‘fs’)

Reading Files

To read files on your computer we use function fs.readFile() function.

Let say you have below  HTML file saved as “demo.html” in the same folder as your node.js

We can create a node.js code to read the file and display it in a web browser.

Save below code as file_demo.xml

Output:

Using Node.js File System Module
Using Node.js File System Module

 

Creating Files  and adding content to them

Node.js File module has below functions for creating and adding content to files.

  • fs.appendFile()-this function creates a file and adds content to it.If the specified file exists, the content is just added to it.Example code.

Output

Using Node.js File System Module

 

 

  • fs.open()-this function takes a ‘flag’ w which means it opens the file for writing.If the file specified does not exists it created and it it exists its opened for writing.

         Example

 

  • fs.writeFile()-this function creates a file and adds the content,if the file exists,its replaced with it content.

    Example

Updating files

You can use fs.writeFile() and fs.appendFile() function to update files with new content.

How to delete files

fs.unlink() function is used to delete files.

Example code

If the file does not exist the function will throw an error.

How to rename existing files

We can rename existing files using  fs.rename() function

Example.

 

About the Author: Eric K

Kenyan Developer and Blogger with Interests in Java,Javascript,Node.js, Wordpress, Android, PHP and Making Money Online. Solving world problems through programming is my passion. Hire me: Email : kawi3462@gmail.com