How to read a properties file in javascript from project directory?

D.S picture D.S · Oct 11, 2013 · Viewed 96.8k times · Source

I'm building a Chrome Packaged App. I want to put the script configuration if a config file in a resource directory and on startup want to read that by Javascript.

For example

  • Project
    • WebContent
      • index.html
      • manifest.json
      • main.js
      • resource
        • config.properties

Here I want main.js to load config.properties file in the beginning and get key-value pairs.

Have anyone done something like this?

Answer

Ben Wells picture Ben Wells · Oct 14, 2013

There is a super simple way to do this, along the lines of sowbug's answer, but which doesn't need any XHR or file reading.

Step 1. Create resource/config.js like so:

gOptions = {
  // This can have nested stuff, arrays, etc.
  color: 'red',
  size: 'big',
  enabled: true,
  count: 5
}

Step 2. Include this file in your index.html:

<!doctype html>
<head>
  <script src="resource/config.js"></script>
  ...

Step 3. Access your options directly from your main.js (or anywhere):

  ...
  if (gOptions.enabled) {
    for (var i = 0; i < gOptions.count; i++) {
      console.log(gOptions.color);
    }
  }
  ...