我如何使用sitemap.js?

时间:2014-10-21 18:11:42

标签: javascript node.js sails.js

我安装了节点模块sitemap.js来为我的网站生成sitemap.xml。但是,我对node / express / sails相当新,所以我不太了解git页面上的说明。在“用法”部分下面的代码应该去哪里?如何执行模块以生成xml?

1 个答案:

答案 0 :(得分:0)

显然这适用于我的表格,但这就是我使用cron创建静态(我每周使用sitemap.xml更新一次)sitemap的方式。

'use strict';

var sm = require('sitemap')
var fs = require('fs');

var photoModel = require('../../models/photo');
var db  = require('../../models/db');

var config = require('../../config');

var hostname = config.siteUrl

var queryParams = {
    active: 1,
    sortOrder: 'desc',
    sortBy: 'relevance',
}

var photoQuery = db.rawSQL([
    'SELECT img_id, tags',
    'FROM images',
    'WHERE active = 1'
]);

function createSiteMap(myURLs) {
    var sitemap = sm.createSitemap({
        hostname: hostname,
        cacheTime: 600000,  //600 sec (10 min) cache purge period 
        urls: myURLs
        });
    fs.writeFileSync("public/sitemap.xml", sitemap.toString());    
    process.exit();
}

function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}

function getPhotos() {
    return new Promise(function(resolve, reject) {
        var siteMapArray = new Array()
        var tags = new Array()
        siteMapArray.push ({ url: '/' , changefreq: 'weekly', priority: 0.8, lastmodrealtime: true, lastmodfile: 'views/home.hbs' },)
        db.sequelize.query(photoQuery, {
            replacements: queryParams
        }).spread(function(makeSiteMap) {
            makeSiteMap.forEach(function(obj) {
                var siteLink = { url: 'photo/' + obj.img_id, changefreq: 'weekly', priority: 0.6, lastmodrealtime: true }
                siteMapArray.push(siteLink);
                obj.tags = obj.tags.split(',').map(function(e) {
                    return e.trim().split(' ').join('+');
                });
                for (var tag in obj.tags) {
                    tags.push(obj.tags[tag])
                }
            });

            resolve (siteMapArray);

            var uniqueTags = uniq(tags);
            for (var tag in uniqueTags) {
                var siteLink = { url: '/search/' + uniqueTags[tag], changefreq: 'weekly', priority: 0.8, lastmodrealtime: true }
                siteMapArray.push (siteLink);
            }

            createSiteMap(siteMapArray);

        });
    });
};

getPhotos();