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.
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.
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.
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:
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”.
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.
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;
This function takes data parameter and prints that data to a console. fs.readFile()
is Node JS FS API. It takes three parameters;
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.
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. 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.
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.
What about ppt and rft files?
- Chapter
Hi, Is it possible to create folder and write file in remote server from my local node server. Please help me on this.
- Krishnaraj
Good polished and lement version liked it.
- Kishan
Good job
- sid