This repository was archived by the owner on Feb 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfetchXMLFeedToJSON.js
More file actions
87 lines (70 loc) · 2.28 KB
/
fetchXMLFeedToJSON.js
File metadata and controls
87 lines (70 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import fsp from "fs/promises";
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { xml2js } from "xml-js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const projectDir = path.resolve(__dirname, "./");
const distDir = path.resolve(projectDir, "public");
export async function fetchXMLFeedToJSON(outputDir, feedUrl, options = {})
{
if (!outputDir || typeof outputDir !== "string")
{
throw new Error("outputDir must be a non-empty string");
}
if (!feedUrl || typeof feedUrl !== "string")
{
throw new Error("feedUrl must be a non-empty string");
}
const filename = options.filename || "xmlfeed.json";
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 15000;
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), timeoutMs);
let xmlText;
try
{
const res = await fetch(feedUrl, {
signal: controller.signal,
headers: { "User-Agent": "RedotEngine/1.0 (+https://redotengine.org)" },
});
if (!res.ok)
{
throw new Error(`Failed to fetch feed: ${ res.status } ${ res.statusText }`);
}
xmlText = await res.text();
}
finally
{
clearTimeout(t);
}
const jsonObj = xml2js(xmlText, {
compact: true,
ignoreDeclaration: true,
ignoreInstruction: true,
ignoreComment: true,
ignoreCdata: false,
ignoreDoctype: true,
trim: true,
nativeType: false,
});
await fsp.mkdir(outputDir, { recursive: true });
const payload = {
source: feedUrl,
generatedAt: new Date().toISOString(),
data: jsonObj,
};
const filePath = path.join(outputDir, filename);
await fsp.writeFile(filePath, JSON.stringify(payload, null, 2), "utf8");
return { filePath, feedUrl };
}
const feedUrl = "https://blog.redotengine.org/feeds/posts/default?alt=rss&max-results=4";
fetchXMLFeedToJSON(path.join(distDir, "data"), feedUrl, {
filename: "blogger-feed.json",
})
.then(({ filePath }) => console.log("Saved:", filePath))
.catch((err) =>
{
console.error(err);
process.exitCode = 1;
});