1

I want to dynamically combine multiple javascript files, each represented as an object with a few functions as such:

// ./src/foo.js
{
   "foo": function() {
       console.log("foo");
   }
}

// ./src/bar.js
{
   "bar": function() {
       console.log("bar");
   }
}

// desired output
{
   "foo": function() {
       console.log("foo");
   },
   "bar": function() {
       console.log("bar");
   }
}

I would like to return a single file which resembles a JSON object. If I were combining strict JSON, the function would look (very roughly) like this:

   var files = ['./src/foo.json', './src/bar.json'];
   var final = {};

   for(var i in files) {
      var srcFile = files[i];
      var json = JSON.parse(fs.readFileSync(srcFile, 'utf8'));
      Object.assign(final, json);
   }

   console.log(JSON.stringify(final, null, 2));

This does not seem to work however, as my files contain functions and comments, which are not strictly allowed in JSON representation. I thus have to store the files as .js files and this approach doesn't work for merging the objects into a single object. How can I read in and merge "JSON" files containing functions?

So my question boils down to 2 parts:

  1. What replaces var json = JSON.parse(fs.readFileSync(srcFile, 'utf8')); to read a javascript object containing functions into the var json variable?
  2. What replaces Object.assign({}, json) to merge the functional objects?
kharandziuk
  • 9,273
  • 9
  • 51
  • 94
CaptainStiggz
  • 1,472
  • 3
  • 21
  • 42

1 Answers1

3

here the first part of the solution:

const fs = require('fs')
const files = ['./foo.js', './bar.js'];
const Promise = require('bluebird');

const final = Promise.resolve(files)
  .map(file => Promise.fromCallback(cb => fs.readFile(file, 'utf-8', cb)))
  .reduce(
    function(acc, file) {
      const obj = eval(`(${file})`)
      return Object.assign(acc, obj)
    },
    {}
  ).then(function(final) {
    console.log(final)
  })

the result:

> node 1.js
{ foo: [Function], bar: [Function] }

Now you need to decide how do you want to represent functions

and the second part you can find here

NB: eval is unsafe but I think in the context of you task it's completely ok

Community
  • 1
  • 1
kharandziuk
  • 9,273
  • 9
  • 51
  • 94