Reading and Writing Files With NodeJS Image Reading and Writing Files With NodeJS

In this tutorial I’m going to be showing you exactly how we can read and write files on our local filesystem using NodeJS.

Reading From Files

Being able to read from files on your local file system can be hugely useful and there are a number of different things you can build on top of this. A log reader, importing information from spreadsheets and xml files or whatever you can think of, being able to read from files is hugely useful.

The FS Package

Create a new file called index.js and add the following:

1
2
3
4
5
6
var fs = require('fs');

fs.readFile('temp.txt', function(err, buf) {
  console.log(buf.toString());
});

Create a temp.txt within the same directory and write in it anything you’d like. Run your script using node index.js and you should see in the console the contents of your file.

Understanding the Code

We’ll step through this with comments.

1
2
var fs = require('fs');

This line does the job of importing the fs package and allowing us to utilize it within our own code.

1
2
3
4
fs.readFile('temp.txt', function(err, buf) {
  console.log(buf.toString());
});

This calls the readFile function asynchronously and then prints the contents of the file to the console.

Returning a Buffer?

If the above code hasn’t worked as expected and you are seeing a buffer being printed out in the terminal then it might be an idea to specify the files encoding. We can do this like so:

1
2
3
4
5
6
var fs = require('fs');

fs.readFile('temp.txt', 'utf-8' ,function(err, buf) {
  console.log(buf.toString());
});

Writing To Files

Now that you’ve got the reading of files down, it’s time to start modifying these files. To do this we’ll be using the same FS package we used in part one.

The Code:

Again create a new file within your current directory and call it write.js and then add the following javascript code:

1
2
3
4
5
6
7
8
9
var fs = require('fs');

var data = "New File Contents";

fs.writeFile('temp.txt', data, function(err, data){
    if (err) console.log(err);
    console.log("Successfully Written to File.");
});

Run this code by executing node write.js in the terminal and then open up temp.txt in your editor, you should now see the new contents of the file.

Was This Post Helpful?
Submit a PR: Edit on Github