Node FS – NodeJS Create File, Read File, Write to File

Filed Under: Node.js

Node FS stands for NodeJS File System module. In my previous post, we have already discussed about how to import a Node JS module using require() call. Before reading this post, please go through this post “Node JS Export and Import Modules” to know require() call usage.

Node FS

In this post, we are going to discuss about Node JS Platform “fs” module. FS Stands for File System. This module is also known as IO or FileSystem or Stream module.

NodeJS FS Module Post Brief

  1. Introduction to Node FS Module
  2. Node JS Create File
  3. Node JS Write to File
  4. Node JS Read File

Introduction to Node FS Module

Node FS Module provides an API to interact with File System and to perform some IO Operations like create file, read File, delete file, update file etc.

Like some Node modules for example “npm”, “http” etc, Node JS “fs” also comes with basic Node JS Platform. We don’t need to do anything to setup Node JS FS module.

Node FS Module import

We just need to import node fs module into our code and start writing IO Operations code.

To import a node fs module;


var fs = require("fs");

This require() call imports Node JS “fs” module into cache and creates an object of type Node FS module. Once it’s done, we can perform any IO Operation using node fs object.

Let us assume that our ${Eclipse_Workspace} refers to D:\RamWorkspaces\NodeWorkSpace.

Now onwards, I’m going to use this variable to refer my Eclipse workspace.

As a Java or DOT NET or C/C++ developers, we have already learned and wrote some IO Programs.

IO or Streams are two types:

  • Write Stream – To write data to a Stream.
  • Read Stream – To read data from a Stream.

Node JS Create File

Now we will discuss about how to create a new file using Node JS FS API.

  1. Create a Node JS Project in Eclipse IDE.
    Node FS Example Project
  2. Copy package.json file from previous examples and update the required things.
    
    {
      "name": "filesystem",
      "version": "1.0.0",
      "description": "File System Example",
      "main": "filesystem",
      "author": "JournalDEV",
      "engines":{
      	"node":"*"
      	}
    }
    
  3. Create a JavaScript file with the following content;

    fs-create-file.js

    
    /**
     * Node FS Example
     * Node JS Create File
     */
    var fs = require("fs");
    
    var createStream = fs.createWriteStream("JournalDEV.txt");
    createStream.end();
    

    Code Description:

    var fs = require("fs") require() call loads specified Node FS module into cache and assign that to an object named as fs.

    fs.createWriteStream(filename) call is used to create a Write Stream and file with given filename.

    createStream.end() call ends or closes the opened stream.

  4. Before executing fs-create-file.js, first observe the filesystem project content and you will notice that “JournalDEV.txt” file is not available.
  5. Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-create-file.js file as shown in below image.

    Node JS Create File

    Notice your project directory contents now, you will notice an empty file named “JournalDEV.txt”.

Node JS Write to File

We will use Node FS API to create a new file and write some data into that. It is continuation to our previous example.

  1. Remove previously created “JournalDEV.txt” from ${Eclipse_Workspace}/filesystem folder
  2. Create a Java Script file with the following content:

    fs-write-file.js

    
    /**
     * Node FS Example
     * Node JS Write to File
     */
    var fs = require("fs");
    
    var writeStream = fs.createWriteStream("JournalDEV.txt");
    writeStream.write("Hi, JournalDEV Users. ");
    writeStream.write("Thank You.");
    writeStream.end();
    

    createStream.write(sometext) call is used to write some text to a file.

  3. Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-write-file.js file as shown below.
    Node JS Write to File
  4. Go to ${Eclipse_Workspace}/filesystem folder and open “JournalDEV.txt” to verify its content.
    Node FS Example, Node.js Write File Example

    Now we have created a new file and write some data into that file.

Node JS Read File

We will use Node FS API to open and read an existing file content and write that content to the console. It is continuation to our previous examples.

Here we are going to use named JavaScript function. Go through this example to understand this.

  1. Create a Java Script file with the following content.

    fs-read-file1.js

    
    /**
     * Node FS Read File
     * Node JS Read File
     */
    var fs = require("fs");
    
    function readData(err, data) {
    	  console.log(data);
    }
    
    fs.readFile('JournalDEV.txt', 'utf8', readData);
    

    Code Description:

    readData() is a JavaScript function which takes two parameters;

    1. err: it’s an error object. When our program fails to open or read data from a file, then FS module writes some error message into this parameter.
    2. data: it’s a variable to hold some data.

    This function takes data parameter and prints that data to a console.

    fs.readFile() is Node JS FS API. It takes three parameters;

    1. file name
    2. file data format to read
    3. A JavaScript function or JavaScript anonymous function

    readFile() reads data from a filename (first parameter) in given format (second parameter) and uses function given at third parameter to do some operation.

    Here we are using a plain JavaScript function as the third Parameter. We will see how to use JavaScript anonymous function in next example.

    In our example, readFile() reads data from “JournalDEV.txt” file and writes to console.

    If we don’t use ‘utf8’ format, then we will get binary data. We will verify this in few moments.

  2. Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-read-file1.js file.

    Node JS Read File Example

    Now we have observed that our code has successfully open a file, reads its content and writes its content to the console.

Node.js read file as binary

Now we are going to use JavaScript anonymous function to read data from a file. Go through this example to understand this. It’s similar to previous fs-read-file1.js example only but with anonymous function. If you are not familiar with JavaScript anonymous functions, please go through some JavaScript tutorial and get some idea.

Create a Java Script file with the following content;

fs-read-file2.js


/**
 * Node FS File System Module
 * Node.js read file example
 */
var fs = require("fs");

fs.readFile('JournalDEV.txt', 'utf8', function(err, data) {
	  console.log(data);
});

Code Description:

Here readFile() is using JavaScript anonymous function to read data from a file and write that file content to the console.

When we run this file, we will get same output as fs-read-file2.js example.

Now remove “utf8” data format to see binary output.


/**
 * Node FileSystem Module  
 * Node JS Read File Binary Data
 */
var fs = require("fs");

fs.readFile('JournalDEV.txt', function(err, data) {
	  console.log(data);
});

Execute above file and observe the output as shown in below image.
Node.js read file as binary data

Bonus TIP: To learn Node JS FS API in depth, please use Enide 2014 Studio and know all available functions and usage as shown below.


[anyFSAPIObject] + Press . (dot) + After dot Press (CTRL + Space Bar)

Node.js FS module Enide IDE

Now we are familiar with Node FS module. We are going to use this knowledge in next posts, especially in HTTP Module post.

Reference: Official Documentation

Comments

  1. Chapter says:

    What about ppt and rft files?

  2. Krishnaraj says:

    Hi,

    Is it possible to create folder and write file in remote server from my local node server. Please help me on this.

  3. Kishan says:

    Good polished and lement version liked it.

  4. sid says:

    Good job

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages