2

I'm working on an express.js app which should load an API definition file (most likely the swagger file in JSON format). Currently I've created a middleware, which should parse the JSON file via fs.readFile() and JSON.parse() in order to check user's permissions on accessing some resource. So basically each time the request is performed, my middleware gets the same JSON file and parses it, which is obviously a piece of extra work. Is it possible to load this JSON file, parse and store it to some internal object in a sort of global configuration and reload it in case it was modified so as not to perform the same operation on each request?

Ostap Lisovyj
  • 180
  • 2
  • 17

2 Answers2

1

Of course, you could create a function like this (pseudo code):

var jsonData=null;

function getConfiguration() {
  if (!jsonData) {
    jsonData= readFileSync(...);
  }
  return jsonData;
}

module.exports.getConfiguration=getConfiguration;

Or, as @AleksandrM commented, you can just "import" it using require:

Community
  • 1
  • 1
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
  • Should this be included in separate middleware? in that case, how to pass it to the appropriate middleware? – Ostap Lisovyj Aug 31 '15 at 09:59
  • I'm not sure if that function could work as on every request the `var jsonData` is set to null, and `if (!jsonData)` gets evaluated every time – Ostap Lisovyj Aug 31 '15 at 10:14
  • No, the variable is only declared (and set to null) once. Calling the function does not reset its value. You can create a node module with that piece of code and import it wherever you need it – Pablo Lozano Aug 31 '15 at 10:45
  • Sorry for misunderstanding - now it works like a charm. The mistake was to use your suggested code **in** `module.exports` function, which indeed gets called on every request, that's my lack of experience with Node and Express. Thanks a million for your help! – Ostap Lisovyj Aug 31 '15 at 11:10
0

This is what worked for me, very much aligned with the answer here

let config_file = path.join(__dirname, 'config.json')
let configJSON = {}


function getConfiguration() {
    jsonfile.readFile(config_file, function (err, obj) {
    if (err) console.error(err)
    console.dir(obj)
    configJSON = obj
})}

Then on app startup

app.listen(port, () => {
  getConfiguration()
  console.log(`App listening at http://localhost:${port}`)
})
Joviano Dias
  • 1,043
  • 10
  • 13