How to store proccess.argv in .js file for later usage

I have config file

module.exports = {
  foo: proccess.argv[2]
}

how can i pass proccess.argv value to this config file to use it later. Im calling it from npm scrips. So far i tried to call via node - node config.js 'bar'. But i guess its obvoius that arg appears only in runtime. So success scenario would be - call config file via node with passed param - call it later from npm script with stored argv value


Solution 1:

You could write the config-object as a json-string to a file and read that file at some later point and parse its content in order to get back an object. Something like (still needs some error-handling of course):

// config.js
const fs = require('fs');

(() => {
    fs.writeFileSync('./config.json', JSON.stringify({
        foo: process.argv[2]
    }));
})();

Call it with node config.js 'bar' and then at some later point you can use it like this in a different script:

// some-other-script.js
const fs = require('fs');

(() => {
    const config = JSON.parse(fs.readFileSync('./config.json'));
    console.log(config); // will log "{ foo: 'bar' }" to the console
})();