Categories
nodejs

Reading from and writing to files in node.js

NodeJS is an awesome platform to build applications in javascript which can run on the server.
It allows you to read n write to files asynchronously and synchronously

Writing Data to files

The easiest way would be write synchronously (i.e. wait till the writing operating is finished)

var fs = require('fs');
fs.writeFileSync('/path/to/some_text.txt', 'some text');

But the preferable way of writing to files will be asynchronous in context of web apps.

var fs = require('fs');
fs.writeFile("/path/to/some_text.txt", "test data!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("file has been saved successfully");
    }
});

In this case the program will continue to execute next instruction without waiting for the file write to complete. Once the file writing is completed, the third parameter (closure ) is executed. Above method overwrite the current file. So if you want to append the data, use