How to read a file

walden systems, javascript, read file, file, i/o
a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm. Alongside HTML and CSS, JavaScript is one of the three core technologies of the World Wide Web.[9] JavaScript enables interactive web pages and thus is an essential part of web applications. The vast majority of websites use it,[10] and all major web browsers have a dedicated JavaScript engine to execute it.

Sometimes you might need to open and read a file. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straight forward method to opening and reading a file.

Strategy to opening and reading a file is straight forward and involves only two steps: First, we will need to include the File System module. Next, we need to read the file using the readFile( ) method.


Here are the steps:

First thing we include the File System module :

var fs = require( 'fs' ) ;


Next, we need to open the file and read it's contents using the readFile( ) method. In this example, we will be opening a text file so we are using "utf8" as the return type:

fs.readFile
(
    SOME_FILE, "utf8", function ( error, data )
    {
        if ( error )
        {
            throw error ;
        }
        console.log( data ) ;
    }
) ;

So here is the full code :

var fs = require( 'fs' ) ;

fs.readFile
(
    SOME_FILE, "utf8", function ( error, data )
    {
        if ( error )
        {
            throw error ;
        }
        console.log( data ) ;
    }
) ;