title: Express/Node.js | Generating a new JSON object from within a glob call
body: <p>I'm very new to JS and I think I'm missing something fundamental regarding the storage of an object state and the structure of nested function calls. </p>
  
  <p>I'm globbing a directory containing many JSON files and I want to load these iteratively and parse the contents to a single JSON object. 
  I'm parsing the contents correctly inside the function, but as I've written it, the object state isn't persisting outside the function.</p>
  
  <pre><code>const glob = require('glob');
  
  const retrieve = (query) =&gt; {
      const dataJSON = {};
      const json_path = saveDir + '/upload/' + query + '/'
      glob(json_path + '*.json', function (er, files) {
          for (index in files) {
              dataJSON[index] = require(files[index])
          }
          // Logging here returns the correct object
          console.log(dataJSON)
          return dataJSON
      });
      // Logging here returns an empty object
      console.log(dataJSON)
      return dataJSON
  
  }
  
  // I need to return the object here
  app.get('/patent', (req, res) =&gt; {
      res.json(retrieve(req.query['q']))
  });
  </code></pre>
  
  <p>Two questions, how do I persist 'dataJSON' outside of glob, and how would I return 'files' from outside of glob?</p>
  
  <p>Ex. for second question</p>
  
  <pre><code>var example = glob("**/*.js", function (er, files) {
    // files is an array of filenames.
  
    return files
  })
  
  console.log(example)
  &gt;&gt;['file1.json', 'file2.json', 'file3.json']
  </code></pre>