« Previous Tutorial Next Tutorial »

Last week, we looked into opening files and manipulating their data using the Node.js file system. This week we're going to continue onward by saving data back to the drive. We'll also look into a couple of handy methods that come along with the basic open/write capabilities.

Let's continue right along using the same server and code that we established last week, except I've removed the console.log lines. Here's what index.js should look like:

const fs = require('fs');
const csv = require('csvtojson');

const rawData = fs.readFileSync('authors.csv');
const authorData = rawData.toString();

csv().fromString(authorData).then((authorJson) => {
  // We'll need to do something here!
});

The first thing we're going to do is use some handy methods to get some information. So inside that function where it says "we'll need to do something here" let's do something … there. Specifically, before we write our file, let's create a directory (if it's not already there) in which to store the file. Replace that comment with this code:

  // Check if the directory exists
  fs.readdir('output', (err, files) => {
    console.log(err);
  });

Go ahead and run that, and you'll get an exciting error in your console. Displaying an error is handy, but not really what we're trying to do. Let's create the directory instead, if it doesn't already exist. Replace the console.log line with this code:

    if (err && err.code === 'ENOENT') {
      fs.mkdir('output', (err) => {
         if (err) {
            return console.log(err);
         }
      });
    }

If you run that, it's going to create our new output folder. Sweet. Let's move on to actually creating the file. We've got our authorJson ready to go … or do we?! Okay, no, we don't. The output generated by csvtojson is actually a JavaScript object, not a JSON string. This is great for manipulating it in the code, but less great for saving it to a file. So let's stringify it. Below the if block you just wrote, add this code:

    const authorJsonString = JSON.stringify(authorJson);

Now we just need fs.writeFile this baby up. Here's the code:

    fs.writeFile('output/authorData.json', authorJsonString, (err) => {
      if (err) {
        return console.log(err);
      }
    });

And there we go! If you check your output folder, you've got a nice JSON file with all of our author data. Just as we'd hoped!

Now, generally there's not a huge need for saving random snippets of JSON, but imagine if you were creating an app that needed to generate physical logs of errors or large amounts of data for your clients to download and ingest via their own processes. Having access to the file system for those reasons is wildly useful. Additionally, having access to the file system facilitates things like conversion apps. Maybe you've got six thousand documents in an old, obscure format. You could hand-convert each one, or you could write a little Node.js app that does the job for you, and organizes them into folders by creation date, or alphabetical order.

So, that's the basics of the file system. There are a bunch of other fs methods available, for doing things like deleting files and directories. I'm happy to cover some more of them next time if you'd like. Just let me know!

See you next time.

As always, you can download example files for each of these tutorials from the JS Quick Hits github repo.

Enjoying these quick hits? You can get them five days early by subscribing to our weekly newsletter.

« Previous Tutorial Next Tutorial »