简体   繁体   中英

How can re-write JS file with data coming from server with node.js (express server)?

I have a static file config.js . Which looks like

UP_CONFIG.RAZOR_CONFIG = {
   "key": "dummy text",
    "currency": "dummy text,
};
UP_CONFIG.NAME = "dummy name"

The data coming form server looks like:

UP.CONFIG:{
    RAZOR_CONFIG:{
      key:"real key",
      currency:"real curr"
    },
    NAME:"real name"
}

How can I re-write config.js files with the value coming from server data changing the structure?

Output I am expecting in config.js file is:

UP_CONFIG.RAZOR_CONFIG = {
   "key": "real key",
    "currency": "real curr,
};
UP_CONFIG.NAME = "real name"

The data you get from the server is not valid JSON and it's not valid JavaScript. You will have hard time parsing it especially if it can change in the future. If on the other hand you used any standard data format for communication - like JSON or YAML or CSV or even XML - then it would be much easier for you to parse and store since you would have standard tools at your disposal.

If you have any control over the data coming from the server then consider changing this format:

UP.CONFIG:{
    RAZOR_CONFIG:{
      key:"real key",
      currency:"real curr"
    },
    NAME:"real name"
}

to this:

{
  "UP_CONFIG": {
    "RAZOR_CONFIG": {
      "key": "real key",
      "currency": "real curr"
    },
    "NAME": "real name"
  }
}

and then you will be able to easily parse it and modify.

Additionally you can directly require() JSON files in Node so it's trivial to use for config in your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM