Node.js Tutorial: Reading and Writing files

Reading and writing files is a very trivial task, no matter what programming language you use you probably have already came across a situation where you had to do it, and it’s not different for node.js developers, luckily node.js makes this task very easy for us, with the file system(fs) module we can easily read files with very few lines of code as the following example:

1
2
3
4
5
6
7
var fs = require('fs');
 
fs.readFile('C:\\file.txt', 'utf8', displayData);  
 
function displayData(err,data){
  console.log(data);
}

In the example above I’ve just used the fs.readFile function to read a file located on my ‘C:\’, besides the file path I also provided the encoding and a callback which will be called once the file content is ready.

Now that we already know how to read files, let’s learn how to write files, it’s as easy as reading them, take a look at the following code:

1
2
3
4
5
6
7
8
9
10
11
var fs = require('fs');
 
fs.writeFile('C:\\file.txt', 'My Content', showMessage);  
 
function showMessage(err){
  if(err) {
    console.log(err);  
  }else{
    console.log('Your data has been successfully written!');    
  }
}

It’s basically the same thing we saw on the first example, except that instead of using the readFile function I used the writeFile, also the second argument is the content I want to write on the file, and once again we have a callback that will execute after the content is written.

If you run this code more than once you should note that before writing your content it erases everything that is already on the file, to prevent this from happening you should use the function appendFile instead of writeFile.

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>