totaljs / framework

Node.js framework
http://www.totaljs.com
Other
4.36k stars 450 forks source link

How to load config file and read config as independent library? #798

Closed aalfiann closed 1 year ago

aalfiann commented 1 year ago

I use total.js v3 as independent on my custom library.

But I can't load and read the config file.

What I did:

require('total.js')

// this didn't load
console.log(F.config.my_data)

here is my config file

my_data: hello world!
petersirka commented 1 year ago

Hi @aalfiann, there is a super hidden method F.$configure_configs() that loads configuration.

The framework loads it automatically if it's loaded with the HTTP server or via the 'LOAD()' method. However, these operations will load everything around Total.js.

aalfiann commented 1 year ago

Sorry I can't to use F.$configure_configs(),

would you give me the example how to use it?

The framework loads it automatically if it's loaded with the HTTP server or via the 'LOAD()' method. However, these operations will load everything around Total.js.

So how to use the LOAD method? I don't use HTTP server for this case.

aalfiann commented 1 year ago

I solve this, by create custom function.

function readConfig (text) {
  const rl = text.split('\n')
  const obj = {}
  for (let i = 0; i < rl.length; i++) {
    if (rl[i].indexOf(':') !== -1 && rl[i].indexOf('#') !== 0) {
      const part = rl[i].split(':')
      const key = part[0].trim()
      const value = part[1].trim()
      obj[key] = value
    }
  }
  return obj
}

// usage
const fs = require('fs')
const text = fs.readFileSync('./config', 'utf8')
console.log(readConfig(text))
petersirka commented 1 year ago

You can use String.parseConfig() method, it returns Object.