Skip to main content

Node.JS - File operation examples

File operations are very common requirements and I thought of providing some simple examples in Node.js. The Node.js provide a module called "fs" which is having all necessary functions for performing file operations. Let's start with very simple examples.
Audience
The examples are very basic and focused for beginners.
Reading and Writing Files
The file system module provide a synchronous and asynchronous functions for reading and writing a file.
Example for reading a file using synchronous function fs.readFileSync.
const fs = require('fs');
const information = fs.readFileSync('files/file1.txt', 'utf8');
console.log(information);

Example for reading a file using asynchronous function fs.readFile.

const fs = require('fs');
const information = fs.readFile('files/file1.txt', 'utf8', (err, information) => {
    if (err) {
        console.log('Error occured while reading a file');
        return;
    }
    console.log(information);
});

Example for creating a file using synchronous function fs.writeFileSync.

const fs = require('fs');

const content = `
The file is created for demonstrating file I/O operation using Node.js
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more 
recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
`;

fs.writeFileSync('files/file-write-sync.txt', content, {
    encoding: 'utf8'
});

console.log('file was created successfully');

Example for creating a file using asynchronous function fs.writeFile.

const fs = require('fs');

const content = `
The file is created for demonstrating file I/O operation using Node.js
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more 
recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
`;

fs.writeFile('files/file-write-async.txt', content, {
    encoding: 'utf8'
}, (err) => {
    if (err) {
        console.log('file was not created!!');
        return;
    }
    console.log('file was created successfully');
});
Now when do you use synchronous and asynchronous function?

The synchronous function will block event loop until finishing their operations, which means the other functions are will be in event loop for a while (waiting for long time) when do you perform complex operations in synchronous mode. The synchronous operation will slow down the application performance and asynchronous functions are mostly advisable in Node.js.

Example for renaming a file.
const fs = require('fs');

fs.rename('files/file1.txt', 'files/file1-rename.txt', (err) => {
    if (err) {
        console.log('file was not renamed successfully');
        return;
    }
    console.log('file was renamed successfully');
});
Example for deleting a file.
const fs = require('fs');

fs.unlink('files/file-write-async.txt', (err) => {
    if (err) {
        console.log('file was not deleted!!');
    }
    console.log('file was deleted!!');
});
Example for checking whether a file is exists.
const fs = require('fs');

if (fs.exists('files/file1.txt')) {
    console.log('File exists');
} else {
    console.log('File does not exists');
}

For some cases we may need to check whether a particular user has access for a directory or files. We can easily do it node and here is an example.

const fs = require('fs');

fs.access('files/file1.txt', fs.constants.R_OK | fs.constants.W_OK, (err) => {
    console.log(err ? 'no access' : 'can read and write');
});

fs.constants is an object which has constant values related to file operations.

fs.constants.R_OK // path can be read by calling process
fs.constants.W_OK // path can be write by calling process
Reading a file using stream

The file system module provide a function called fs.ReadStream for reading a file using streams. We need to open a stream and listen for events for reading a data and this is desired method for reading big size files. Here is an example.

const fs = require('fs');

const stream = fs.ReadStream('files/file1.txt');

stream.on('data', (chunk) => {
    console.log(`Received ${chunk.length} bytes of data.`);
});

stream.on('end', () => {
    console.log('No more data available for read');
});

stream.on('error', (err) => {
    console.log(`some error occured while reading a file ${err}`);
});

Writing a file using stream

The file system module provide a function called fs.WriteStream which is similar to read stream method. This allow us to open a stream and write a chunk of data. Here I am providing a simple example for copying a file using write stream method.

const fs = require('fs');

const source = fs.ReadStream('files/file1.txt');
const dest = fs.WriteStream('files/file2.txt');

source.on('data', (chunk) => {
    dest.write(chunk);
});

source.on('end', () => {
    console.log('File was copied successfully');
    dest.end();
});

Reading a file using ReadLine module

The ReadLine module is helpful for reading a data from readble stream one line at a time. Here is an example will read a content from file (line by line) and print it in console.

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
    input: fs.createReadStream('files/file1.txt')
});

rl.on('line', (line) => {
    console.log(line);
});

rl.on('close', () => {
    console.log('done!!');
});

I have provided some simple examples of file operations using Node. Actually Node is having more capabilities for handling I/O and look at official documentation for more information.

Comments

oshingrace said…
This comment has been removed by the author.

Popular posts from this blog

Getting key/value pair from JSON object and getting variable name and value from JavaScript object.

 Hi, I had faced one issue like this. I have an JSON object but I don't know any key name but I need to get the all the key and corresponding value from JSON object using client side JavaScript. Suddenly I wondered whether it's possible or not, after that I had done lot of workaround and finally got this solution. See the below example.    function getKeyValueFromJSON() {     var jsonObj =  {a:10,b:20,c:30,d:50} ;     for ( var key in jsonObj) {       alert( "Key: " + key + " value: " + jsonObj[key]);     }  }  In this example I have created the one json array as string, and converted this string into JSON object using eval() function. Using for-each loop I got all the key value from jsonObj, and finally using that key I got the corresponding value.  Finally I got the alert like this,    Key: a value:10    Key: b value:20    Key: c value:30    Key: d value:50  During this workaround I got one more idea, using this same way I got

Simple Login Application Using Spring MVC and Hibernate – Part 1

 I hope developers working in web application development might hear about MVC architecture. Almost all technologies provide support for MVC based web application development, but the success is based on many factors like reusable of the code, maintenance of the code, future adaption of the code, etc..,  The success of the Spring MVC is “ Open for extension and closed for modification ” principle. Using Spring MVC the developers can easily develop MVC based web application. We don’t need any steep learning curve at the same time we need to know the basics of spring framework and MVC architecture. The Spring MVC consists of following important components. 1. Dispatcher servlet 2. Controller 3. View Resolver 4. Model Spring MVC - Overview  The overall architecture of Spring MVC is shown here.  1. When “Dispatcher Servlet” gets any request from client, it finds the corresponding mapped controller for the request and just dispatches the request to the corresponding contro

Simple Login Application Using Spring MVC and Hibernate – Part 2

 I hope you have visited my part1 of my tutorial . Let’s see the steps for integrating hibernate framework into Spring MVC. Here I have used MySQL database. I have created one database called “ springmvc ” and created one table called “ user ” with userid, username, password fields.  I have inserted some records into table like this. Step 1: Creating User POJO class.  We need to create a User POJO class for mapping user table. Ok let’s create it. Step 2: Creating hibernate mapping xml file for user class.  In hibernate we need to create hibernate mapping xml file for all domain class for mapping into corresponding database table. Instead of creating xml file you can use annotation for mapping domain class into database table. This is my mapping xml document created for mapping our user domain class into user database table. Step 3: Creating authenticate service class.  The method “verifyUserNameAndPassword” present in “AuthenticateService”