Reading a file in Node.js

Node.js provides two simple methods to read a file in sync and async. Reading a file in sync comes in handy if you’ll read a config file right before the the actual programs should run.

Reading a file async:

fs = require('fs');

fs.readFile('./file.txt', 'utf8', function(err, data){
    if(err){
        return console.log(err);
    };

    console.log(data.toString());
});

Reading a file in sync:

fs = require('fs');

var fileContent = fs.readFileSync('./file.txt').toString()

Reading a large file one line at a time:

If you’ll read a very large file, I recommend to read the file with createReadStream and then pass the stream to the module lazy, which treats all incoming events as a list.

fs = require('fs');
var lazy = require("lazy")
new lazy(fs.createReadStream('./webSites.txt'))
     .lines
     .forEach(function(line){
         console.log(line.toString());
     }
);
Advertisements
This entry was posted in Development, Node.js and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s