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?

1
  • 3
    FYI you can require json. Commented Aug 31, 2015 at 10:17

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Should this be included in separate middleware? in that case, how to pass it to the appropriate middleware?
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
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
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!
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}`)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.