Tutorial

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

Published on August 4, 2022
author

Rambabu Posa

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

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 functionreadFile() 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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Rambabu Posa

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 2, 2019

What about ppt and rft files?

- Chapter

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 12, 2019

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

    - Krishnaraj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 27, 2017

      Good polished and lement version liked it.

      - Kishan

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 8, 2015

        Good job

        - sid

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.