koa添加sitemap

获取sitemap

 .get('/sitemap.xml', async (ctx,next) => await getSiteMap(ctx,next))
 ...
 async function getSiteMap(ctx,next) {
    let sm = new SitemapStream();
    createReadStream('sitemap.xml')
        .pipe(new XMLToSitemapItemStream())
        .pipe(sm)
    let res = await streamToPromise(sm);
    ctx.set('Content-Type', 'application/xml')
    ctx.body = res;
}

更新sitemap

async function updateSiteMap(siteMapList=[]) {
        const sitemap = new SitemapStream({ hostname: 'http://siyuweb.com' });
        const writeStream = createWriteStream('./sitemap.xml');
        sitemap.pipe(writeStream);
        siteMapList.forEach(item=>sitemap.write(item));
        await sitemap.end();
}

参考:

sitemap的npm包 sitemap的github文档 write-to-file