Node FS – NodeJS Tutorial

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

  • Introduction to Node FS Module
  • Node JS Create File
  • Node JS Write to File
  • 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;

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.

Create a Node JS Project in Eclipse IDE.

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":"*"
  	}
}

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.

Before executing fs-create-file.js, first observe the filesystem project content and you will notice that “JournalDEV.txt” file is not available.

Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-create-file.js file as shown in below image.

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.

Remove previously created “JournalDEV.txt” from ${Eclipse_Workspace}/filesystem folder

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.

Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-write-file.js file as shown below.

Go to ${Eclipse_Workspace}/filesystem folder and open “JournalDEV.txt” to verify its content.

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.

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;

  • 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.
  • 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;

  • file name
  • file data format to read
  • 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.

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

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.

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)


Now we are familiar with Node FS module.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

Hibernate SessionFactory

JavaScript, Tutorial
Hibernate SessionFactory Hibernate SessionFactory is the factory class through which we get sessions and perform database operations. Content1 Hibernate SessionFactory2 Conclusion Hibernate SessionFactory Hibernate SessionFactory provides three methods through which…