In this article i will teach you how to access File System in node.js
.
Using File System we can able to read and write file in node.js
.For Accessing the File System we need to include the File System library.
In Node.js we use require
command for importing the libraries.
For example,Now we need to include the file System library in node.js,so that we use the following command to include filesystem
var fs = require("fs")
Now we succesfully included the file system.
Using File System we can able to access the File I/O.
Some of the Functions comes under File System
fs.write(fd, buffer, offset, length, position, callback)
fs.writeSync(fd, buffer, offset, length, position)
fs.read(fd, buffer, offset, length, position, callback)
fs.readSync(fd, buffer, offset, length, position)
fs.readFile(filename, [options], callback)
fs.readFileSync(filename, [options])
fs.writeFile(filename, data, [options], callback)
fs.writeFileSync(filename, data, [options])
For all functions see the below official website link
http://nodejs.org/api/fs.html
Now we will see how to read file from synchronous and asynchronous way.
Read File in Node.js
I already mentioned in file system we can able to read file by synchronous way and also asynchronous way.
Next article i will clearly explain what is synchronous and asynchronous function.
Now we will go to see for how to read file .
First create one text file with contain some datas. File Name - > sample.txt
- Inside Content -> This is the text file
Then Create a javascript file for accessing the read operation.
So i will create the file name as read.js
Then Write the below code for asynchronous function
var fs = require("fs");
console.log("Start Reading");
fs.readFile("sample.txt","utf8",function(error,data){
console.log(data);
});
console.log("stoped");
Command for run the file in Ubuntu : node read.js
Output for the above program
start
stoped
This is the text file
Above function is a asynchronous function.The main aim of asynchronous is non-blocking.
See the same example for Synchronous function
var fs = require("fs");
console.log("start");
var content = fs.readFileSync("sample.txt","utf8");
console.log(content);
console.log("stoped");
Output for above program
start
This is the text file
stoped
Synchronous method is a normal flow of execution.See more information about the file system in below link
http://nodejs.org/api/fs.html
Also the next article i will explain what is Synchronous and Asynchronous Function.