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:
- What replaces
var json = JSON.parse(fs.readFileSync(srcFile, 'utf8'));
to read a javascript object containing functions into thevar json
variable? - What replaces
Object.assign({}, json)
to merge the functional objects?