a blog for those who code

Monday 9 February 2015

Reading and Writing to file simultaneouly in Nodejs

In this post we will discuss about writing to file and then reading it simultaneously in Nodejs. Writing to a file and Reading the contents of a file into memory is a very common programming task, the Node.js core API provides methods to make this trivial.

The easiest way to read the entire contents of a file is fs.readFile and the easiest way to write into the file is fs.writeFile.

According to http://nodejs.org/,

fs.readFile - Asysnchronously reads the entire contents of a file.
fs.writeFile - Asynchronously writes data to a file, replacing the file if it alraedy exists.
fs.createWriteStream - Returns a new WriteStream object

Writing to a file continously

var fs = require('fs'), count=0;
var stream = fs.createWriteStream('file.txt',{flags:'a'});
stream.on('open', function() {
 console.log('Writing to a file every 2 seconds...');
 setInterval(function() { stream.write((++count)+ 'count!\n');},2000);
});



Reading from the file Simultaneously

var fs = require('fs'), size = 256, bytes = 0, file;
fs.open('file.txt', 'r', function(err,f){ file = f; readfromfile(); });
function readfromfile() {
 var fileStats = fs.fstatSync(file);
 if(fileStats.size < bytes + 1) {
  setTimeout(readfromfile,3000);
 }
 else {
  fs.read(file, new Buffer(size), 0, size, bytes, capturefilecontents);
 }
}function capturefilecontents(err, bytecount, buff) {
  console.log('Read', bytecount, 'bytes');
  console.log(buff.toString('utf-8',0,bytecount));
  bytes  += bytecount
  process.nextTick(readfromfile);
}



Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

1 comment: