Read RSS Feed on Cloudflare Workers
When utilizing Cloudflare Workers, it can be difficult to use npm packages due to runtime differences. However, to create an RSS feed reader application, one can use the fetch API and htmlparser2 library for Cloudflare Workers. The example code provided showcases how to parse a feed and return a JSON response containing the title, description, datetime, and href of each item in the feed.
広告ここから
広告ここまで
目次
When we use Cloudflare Workers, sometime we cannot use the npm package because of the runtime difference.
If you want to make a RSS feed reader application on Cloudflare Workers, we can use fetch API
and htmlparser2
library.
Example code
import { parseFeed } from "htmlparser2";
export default {
async fetch(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext
) {
const response = await fetch('https://qiita.com/motchi0214/feed.atom')
if (!response.ok) {
return new Response(JSON.stringify([]))
}
const htmlString = await response.text()
const feed = parseFeed(htmlString)
if (!feed) {
return new Response(JSON.stringify([]))
}
const items = feed.items.map((data: any) => {
return {
title: data.title,
description: data.content,
datetime: data.isoDate,
href: data.link,
}
})
return new Response(JSON.stringify(items))
},
};