Node.js: how to create a sitemap

Node.js: how to create a sitemap

In this article we will see how to generate the sitemap of a website with Node.js.

In this article we will see how to generate the sitemap of a website with Node.js.

We can use the sitemap-genrator NPM module that performs a scan on a website and detects the internal URLs and finally generates a sitemap.xml file asynchronously.

Being asynchronous, this module supports a series of events that we can use to monitor the progress of the generation of the sitemap.

The first step is to include the module and initialize it by passing the URL of the website to be scanned.

'use strict';

const SitemapGenerator = require('sitemap-generator');

const generator = SitemapGenerator('https://site.tld', {
  stripQuerystring: false
});

Then we can check when a new URL is identified by using the add event.

generator.on('add', url => {
  console.log(`Found ${url}`);
});

We can also check if a URL returns a HTTP error with the error event.

generator.on('error', error => {
    const {code, message, url} = error;
    const msg = `Error with ${url}: ${code} ${message}`;
    console.error(msg);
});

When the sitemap has been generated, the done event is invoked.

generator.on('done', () => {
  console.log('Sitemap created');
});

To start the generation process, we can invoke the start() method:

generator.start();

The sitemap.xml file will be generated in the same directory from which we run our code or in the path specified by the filepath option.