I'm writing an npm module that needs to take a configuration file as command line arguments. Currently I have it working with a json file like so:
const configurationObject = JSON.parse(await readFile(argv.configPath, 'utf8'));
With this I can run my module like so:
myModule --configPath "./source/to/config.json"
Now I would like to do the same, but using a .js file as the configuration file.
How do I parse that file and store the resulting object to a variable? I've looked into the npm package acorn
, but parsing with acorn just gives me an AST, but I can figure out how to turn that into executable code?
// This results in a string containing the js file contents
// (readFile is fs.readFile wrapped in a Promise)
const fileInput = await readFile(argv.configPathJs, 'utf8');
// Gives me an object structure breaking down the code into an AST
acorn.parse(fileInput, {ecmaVersion: 2020});