I have a config file which has the following format from a file:
define([], function () {
return {
productItems: {
item1: ['Apple', 'Ball', 'Car'],
item2: ['Dog', 'Elephant', 'Frog'],
item3: ['Goat', 'Hotel', 'Indian']
},
};
});
I have tried JSON.parse() and unfortunately it does not read or not parsing, might be because of the wrong format.
I also used the File System module but I cannot get the proper values with the following code:
const getProductItems = () => {
if (fs.existsSync(configPath)) {
const fileData = fs.readFileSync(configPath, 'utf8');
const productItems= fileData.match(/productItems: {(s+.+s+)+}/);
return productItems;
}
}
console.log(getProductItems);
It only returned the function and not the values. How am I going to get the item1, item2 and item3 values out of this custom js file?
2
Answers
I don’t know if I understood correctly, but the main problem why you are not getting the data is beacuse for that you will need to call function define(), so that returns the data you need, the better approach for this is if you are willing to change your configuration, so you just make it like this
You can load AMD modules using requirejs.
This assumes the code you provided is stored in a file called config.amd.js
It is asynchronous so you need to handle callbacks in the usual way.
An alternative approach, which is probably less reliable, would be to strip off the AMD syntax using regular expressions and then run the remaining code through a JSON5 parser.
This seems to work with your code, but isn’t suitable as a generic AMD module parser.
That said, I strongly recommend rewriting the config file to use JSON or be a CommonJS or ECMAScript module. AMD is sufficiently unusual it will probably be a maintenance issue going forward (as new people have to maintain the code and also won’t recognise the format).