Search code examples
gulpsitemapcheerio

Using lastmod as a function within gulp-sitemap with cheerio


I'm attempting to use the lastmod function in conjunction with cheerio (or gulp-cheerio) to pull a value from a meta tag from each file in the stream to populate this lastmod entry.

var gulp = require('gulp');
var cheerio = require('cheerio');
var sitemap = require('gulp-sitemap');

gulp.task('sitemap', function() {
    return gulp.src(['/prod/**/*.html',])

    .pipe(sitemap({ 
        siteUrl: 'https://www.somewhere.com',
        lastmod: function(file) {

            var $ = cheerio.load(body);
            var lastmodValue = $('head > meta[name="dc.date"]').attr('content');

            return lastmodValue.toString().trim();
        }
    }))

    .pipe(gulp.dest('/prod'));
});

This works fine if I hardcode a var before the return and comment out the cheerio statements. Gulp-sitemap lastmod instructions here: https://github.com/pgilad/gulp-sitemap#lastmod


Solution

  • Found my issue - Here's the code that works:

    .pipe(sitemap({ 
            siteUrl: 'https://www.somewhere.com', 
            lastmod: function(file) {
    
                var $ = cheerio.load(file.contents);
                var lastmodValue = $('head > meta[name="dc.date"]').attr('content');
    
                return lastmodValue.toString().trim();
          }
        }))