Red Green Repeat Adventures of a Spec Driven Junkie

TWIL - JavaScript Object Loading

Kat Chuang inspired me to write a short article between article weeks.

tldr; This Week I Learned that JavaScript Objects can be loaded from a file quickly by using: var object = require('./object.json');

Why?

I ran into a situation where a JavaScript object had to be persisted to disk and read back if the application restarted. Instead of creating a file format for the object, I persisted the object using JavaScript’s own notation JSON:

fs.writeFileSync('./object.json', JSON.stringify(object));

With every write, there’s a read and the equivalent would be:

var object = JSON.parse(fs.readFileSync('./object.json'));

Which isn’t all that bad, but I found:

var object = require('./object.json');

To be a pretty sweet way to load a JavaScript object from file because:

  1. There is no need to parse the file using an extra call like: JSON.parse(file);.
  2. No need to instantiate a file handle like fs = require('fs'); in order to load the file.
  3. Less code in the line.

Requirement

One requirement for this technique: the file must be valid JSON!!! Since the file is created by a JavaScript application, I can be sure the format is correct. If the file was created by a person I would probably default to the fs.readFileSync technique to make sure JSON.parse passes.

Downside

One downside I’ve seen is an exception will be thrown if the file is not there. So, I used a try/catch block to create a new object if the file does not exist:

1
2
3
var object;
  try { object = require('./object.json'); }
  catch(error) { object = {}};

This Week I Learned

TWIL: if there’s a guarantee the file loading is a JavaScript Object which I want to use right away (like a config file!) and I don’t want to be dealing with parsing the file, I will use:

var object = require('./object.json');