fetch-prompts.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import fetch from "node-fetch";
  2. import fs from "fs/promises";
  3. const RAW_FILE_URL = "https://raw.githubusercontent.com/";
  4. const MIRRORF_FILE_URL = "https://raw.fgit.ml/";
  5. const RAW_CN_URL = "PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh.json";
  6. const CN_URL = MIRRORF_FILE_URL + RAW_CN_URL;
  7. const RAW_EN_URL = "f/awesome-chatgpt-prompts/main/prompts.csv";
  8. const EN_URL = MIRRORF_FILE_URL + RAW_EN_URL;
  9. const FILE = "./public/prompts.json";
  10. const timeoutPromise = (timeout) => {
  11. return new Promise((resolve, reject) => {
  12. setTimeout(() => {
  13. reject(new Error('Request timeout'));
  14. }, timeout);
  15. });
  16. };
  17. async function fetchCN() {
  18. console.log("[Fetch] fetching cn prompts...");
  19. try {
  20. // const raw = await (await fetch(CN_URL)).json();
  21. const response = await Promise.race([fetch(CN_URL), timeoutPromise(5000)]);
  22. const raw = await response.json();
  23. return raw.map((v) => [v.act, v.prompt]);
  24. } catch (error) {
  25. console.error("[Fetch] failed to fetch cn prompts", error);
  26. return [];
  27. }
  28. }
  29. async function fetchEN() {
  30. console.log("[Fetch] fetching en prompts...");
  31. try {
  32. // const raw = await (await fetch(EN_URL)).text();
  33. const response = await Promise.race([fetch(EN_URL), timeoutPromise(5000)]);
  34. const raw = await response.text();
  35. return raw
  36. .split("\n")
  37. .slice(1)
  38. .map((v) => v.split('","').map((v) => v.replace(/^"|"$/g, '').replaceAll('""','"')));
  39. } catch (error) {
  40. console.error("[Fetch] failed to fetch en prompts", error);
  41. return [];
  42. }
  43. }
  44. async function main() {
  45. Promise.all([fetchCN(), fetchEN()])
  46. .then(([cn, en]) => {
  47. fs.writeFile(FILE, JSON.stringify({ cn, en }));
  48. })
  49. .catch((e) => {
  50. console.error("[Fetch] failed to fetch prompts");
  51. fs.writeFile(FILE, JSON.stringify({ cn: [], en: [] }));
  52. })
  53. .finally(() => {
  54. console.log("[Fetch] saved to " + FILE);
  55. });
  56. }
  57. main();