0

I have a constants.js file like that:

var keyvalues = {
    "var1": 0.08,
    "var2": 0.08,
    "var3": 0.07,
    "var4": 0.065
}

And I want to change value from another js file.

My app.js file like that:

app.post('/updateValue', (req, res)=>{
    let a = constants.keyvalues
    const existingKey = req.body.key;
    const newValue = req.body.newvalue;
    
    constants.keyvalues[existingKey] = newValue; =======> (1)
})

(1) : in this line I want to update value from constant.js file.

And my app.js file will on production stage. I want to use this endpoint for update some values physically.

What is the right way for changing values on constants.js file from app.js file?

akasaa
  • 544
  • 2
  • 14
  • https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file – Ertuğrul Karababa Apr 04 '21 at 16:06
  • They're not really constants if they can change, eh? Do they need to persist across restarts of the service? If so you need to write those values somewhere (file, database, etc.) and reload them when things start up. – Joe Apr 04 '21 at 16:07
  • Does this answer your question? [Is it possible to use JavaScript in one document to change HTML in another?](https://stackoverflow.com/questions/7493689/is-it-possible-to-use-javascript-in-one-document-to-change-html-in-another) – Ahmed Gaafer Apr 04 '21 at 16:11
  • @ahmed gaafer as with the answer that I deleted. I didn't notice the node.js tag on the question so the your link and my answer doesn't work the same. He needs to do the module export stuff like crashes answer below – kaladin_storm Apr 04 '21 at 16:18
  • Just changing the value of a variable in memory will not actually change the value hardcoded in you javascript program for this variable - and thus the change will not persist across program restarts. You would need to read these values from a configuration file, and save back any changes there. – IAmDranged Apr 04 '21 at 16:44
  • It is better to keep this constants values in db table/collection. So It would be easy to update according by API, In case of need – Ashish Sharma Apr 04 '21 at 17:15

1 Answers1

0

You'll have to export the object.

If you're working with ES5, use

let keyValues = {...};
module.exports = {keyValues}

ES6 equivalent:

let keyValues = {...};
export {keyValues}; 

In the file where you want to access the object, use this

const {keyValues} = require("path/to/constants");
console.log(keyValues)
keyValues[key] = value

ES6 Equivalent:

import {keyValues} from 'path/to/constants';
console.log(keyValues)
keyValues[key] = value
Dharman
  • 21,838
  • 18
  • 57
  • 107
Crash0v3rrid3
  • 352
  • 1
  • 5