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

Ext JS 4 – Creating web page using Ext.container.Viewport class and region propery

The Ext.container.Viewport is used for creating general web page and region property is used for splitting web page into different parts. Ext.container.Viewport is a specialized container represents the viewable area of the application (the browser area). It render itself to the document body, there is no need for providing renderTo property and it automatically sizes itself to size of the browser viewport. The viewport also re-size the child elements based on view area(based on browser width and height). The default layout of the viewport is border layout and we can customize this property according to our requirements. The viewport does not provide any scrolling. If necessary, the child elements(generally panels) within viewport needs to provide a scroll feature by using autoScroll property. See the below example for better understanding. This is Home.js file placed into app/view folder. Ext.define('MyApp.view.Home', { extend : 'Ext.container.Viewport&#

Getting servlet init parameter that is defined in web.xml

1. Create a new dynamic web project using eclipse. 2. Create a one new servlet and include the following code. package com.controller ; import java.io.IOException; import javax.servlet .ServletConfig; import javax.servlet .ServletException; import javax.servlet .annotation.WebServlet; import javax.servlet .http.HttpServlet; import javax.servlet .http.HttpServletRequest; import javax.servlet .http.HttpServletResponse; @ WebServlet ( "/LoginController" ) public class LoginController extends HttpServlet {                 private static final long serialVersionUID = 1L;                 public LoginController() {         super ();     }     protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {                                 ServletConfig config = getServletConfig ();                                 System.out.println( "Init parameter user nam

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