The Cloudflare Worker (javascript) to fetch objects in your R2 bucket, then export the objects names and links as json, then convert it to final markdown format.
The reason I do this is: I can have all the objects (files) names and urls exported, and I can just markdown to my website, very helpful, will save a lot of time.
Code was initially written by me but it did not work proerly for converting, but I got the help and made it work (see credit section).
Javascript:
1var src_default = {2 async fetch(request, env) {3 console.log('Listing objects in R2 bucket);4 const listResponse = await env.R2_BUCKET.list({5 prefix: "",6 delimiter: ""7 });8 const objects = listResponse.objects;9 const markdownLinks = objects.map((obj) => `[${obj.key}](https://file.talesofstar.com/${encodeURIComponent(obj.key)})`).join('\n\n');10 console.log("Markdown Links:", markdownLinks);11 return new Response(markdownLinks, {12 headers: {13 "Content-Type": "text/plain"14 }15 });16 }17 };18 export {19 src_default as default20 };Explain:
-
We need to bind (connect) the R2 bucket in Worker dashboard, bind name is “R2_BUCKET” and the choose your R2.
-
Modify the subdomain in code, in this example my R2 subdomain is “file.talesofstar.com”.
Is this good? You can make it without specifying subdomain (urls) definitely. I am using a new different version now (code by AI). But they work like same.
Credit:
Thanks to @Space (Cloudflare Discord Server) for the help. It’s finally working with the help.
Links: