2
function getSitemapURLs( file ) {
  var urls = [];

  fs.readFile( file, ( err, data ) => {
    if ( err ) throw err;

    parser.parseString( data, ( err, result ) => {
      result = result.urlset.url;

      for ( var i = 0; i < result.length; i++ ) {
        urlObj = result[i];

        for ( var key in urlObj ) {
          if ( 'loc' != key) continue;

          // TODO: Improve how this key is accessed. Brittle.
          urls.push(urlObj[key][0]);
        }
      }
    });

  });
  return urls;
}

I'm running getSitemapURLs from a different file after requiring the method. If I console.log( urls ) from within the parseString closure, it returns the expected value, an array of URLs.

Currently, when calling this from the index, I'm getting an empty array returned. This seems to be a scoping issue I've created. Can somebody help me scope this correctly so I can return the array of URLs?

This is what my index.js file is looking like, the file it is called from:

// Utility Methods
const getDomainParts = require('./utility/sitemap.js').getDomainParts,
      setSitemap     = require('./utility/sitemap.js').setSitemap,
      getSitemapURLs = require('./utility/sitemap.js').getSitemapURLs;

// Site Vitals
// Actual URL kept out of StackOverflow for privacy
const baseUrl   = 'https://www.xyzurl.com';
const directory = getDomainParts( baseUrl );

// Init Tests

( async () => {

  const sitemap = setSitemap( baseUrl, directory );
  await sitemap;
  const urls    = getSitemapURLs(`./sites/${directory}/sitemap.xml`);

  console.dir( urls );

} )();

0 Answers0