We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
sitemap是一个用于生成站点地图的库,官方提供了express 和生成文件的例子,而我用的网站是基于fastify构建的,需要对其进行修改 fastify代码
const app = fastify({ logger: !isProduction, trustProxy: true }) app.get('/sitemap.xml', SiteMap)
siteMap.ts
import { FastifyReply, FastifyRequest } from 'fastify' import { createReadStream, createWriteStream, existsSync } from 'fs' import { join, resolve } from 'path' import { SitemapStream } from 'sitemap' import { pipeline } from 'stream' import { createGzip } from 'zlib' let postCount = 0 export async function SiteMap(request: FastifyRequest, reply: FastifyReply) { reply.raw.setHeader('content-type', 'application/xml') reply.raw.setHeader('Content-Encoding', 'gzip') const count = await getPosts.count()//获取文章数量 if (existsSync(resolve('./sitemap.xml')) && count === postCount) {//已生成并且文章数量没变就直接读取文件 createReadStream(resolve('./sitemap.xml'), { encoding: 'utf8' }).pipe(reply.raw) return reply } postCount = count//更新文章数量 try { const smStream = new SitemapStream({ hostname: 'www.xx.com' }) const streamPipe = smStream.pipe(createGzip()) const posts = getPosts() //create xml stream and pipe const xmlFile = createWriteStream(resolve('./sitemap.xml')) pipeline(smStream, xmlFile, (err) => { if (err) console.log(err) }) //write data to smStream posts.map((post) => { smStream.write({ url: join('/post', post.id), // changefreq: 'daily', lastmod: post.updateAt, priority: post.priority, }) }) //end smStream write and close write stream smStream.end() xmlFile.close((err) => { if (err) console.log(err) }) streamPipe.pipe(reply.raw) return reply } catch (e) { console.error(e) reply.status(500).send() } return }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
sitemap是一个用于生成站点地图的库,官方提供了express 和生成文件的例子,而我用的网站是基于fastify构建的,需要对其进行修改
fastify代码
siteMap.ts
The text was updated successfully, but these errors were encountered: