1

i've build my first Node app in which i need to use 5-10 global variables a lot. The thing is i would like to be able to change those values without restarting the server.

So what i though was setup an interval and update those files either from a ( JSON ? ) file or through a couple of queries to the database.

Now what would be my better option here ? Both mysql and read file modules are used in the app.

Security based wouldn't it be best to place the json file behind the public folder and read from that ? Although without sql injection being possible i think in the DB should be pretty safe too.

What do you guys think ?? Still a newbie in Node JS.

Thanks

LefterisL
  • 1,132
  • 3
  • 17
  • 37

2 Answers2

2

With yamljs, the overhead is that you will need to install it. From your question, it seems you are already using a bunch of 3rd party modules in your app.

Why not use something that is a part of node.js itself?

Use the fs module.

Example:

var fs = require('fs');
var obj;
fs.readFile('myData.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
});

Docs: https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
1

A common technique for passing configuration variables to a server is via a YAML file. Normally this file is read once when the server starts but you could periodically query they file to see when it was last updated and if the file was changed update the configuration variables currently in use.

yamljs

YAML = require('yamljs');
config = YAML.load('myfile.yml');

then you can periodically check the last time a file was modified using the mtime property of fs.stat

fs.stat(path, [callback])

If you find that the last modified time has changed then you can re-read the YAML file and update your config with the new values. ( you will probably want to do a sanity check to make sure the file wasn't corrupted etc. )

If you don't want to write the file watching logic yourself I recommend checking out chokidar

// Initialize watcher.
var watcher = chokidar.watch('myfile.yml', {
  ignored: /[\/\\]\./,
  persistent: true
});

// Add event listeners.
watcher.on('change', function(path) { 
    // Update config
})
pwilmot
  • 586
  • 2
  • 8
  • Pretty much what i was looking at!! Thank you – LefterisL Nov 29 '15 at 22:25
  • In this case you will need to install `yamljs` module which is 3rd party. Why not use just a simple JSON? I would recommend using `fs` module which is a part of node. – Rahul Desai Nov 29 '15 at 22:30
  • Here is a good answer for some of the pros of using yaml http://stackoverflow.com/questions/1726802/what-is-the-difference-between-yaml-and-json-when-to-prefer-one-over-the-other?answertab=votes#tab-top – pwilmot Nov 29 '15 at 22:34