Skip to content

Instantly share code, notes, and snippets.

@jiahut
Last active July 9, 2025 14:58
Show Gist options
  • Save jiahut/17a621f1d4dcd8144c10fbb73ff2d558 to your computer and use it in GitHub Desktop.
Save jiahut/17a621f1d4dcd8144c10fbb73ff2d558 to your computer and use it in GitHub Desktop.
@echo off
REM dns-updater.cmd - Windows wrapper to run dns-updater.bundle.js with bun
REM Usage: dns-updater.cmd [args]
REM Determine the directory of this script
set SCRIPT_DIR=%~dp0
REM Execute the bundled script using bun
bun "%SCRIPT_DIR%dns-updater.js" %*
#!/usr/bin/env bun
// @bun
// dns-updater.ts
import { promises as fs } from "fs";
function printHelp() {
console.error(`Usage: dns-updater.ts --zone ZONE --record RECORD --type TYPE --name NAME --content CONTENT [--ttl TTL] [--token-file PATH]`);
process.exit(1);
}
function parseArgs() {
const args = {};
const argv = process.argv.slice(2);
let i = 0;
while (i < argv.length) {
const arg = argv[i++];
switch (arg) {
case "-z":
case "--zone":
args.zone = argv[i++];
break;
case "-r":
case "--record":
args.record = argv[i++];
break;
case "-t":
case "--type":
args.rtype = argv[i++];
break;
case "-n":
case "--name":
args.name = argv[i++];
break;
case "-c":
case "--content":
args.content = argv[i++];
break;
case "--ttl":
args.ttl = parseInt(argv[i++], 10);
break;
case "--token-file":
args.tokenFile = argv[i++];
break;
case "-h":
case "--help":
printHelp();
default:
console.error(`Unknown argument: ${arg}`);
printHelp();
}
}
if (!args.zone || !args.record || !args.rtype || !args.name || !args.content) {
printHelp();
}
const homeDir = process.env.HOME || process.env.USERPROFILE;
return {
zone: args.zone,
record: args.record,
rtype: args.rtype,
name: args.name,
content: args.content,
ttl: args.ttl ?? 1,
tokenFile: args.tokenFile ?? `${homeDir}/.cloudflare-token`
};
}
async function main() {
const args = parseArgs();
let token;
try {
token = (await fs.readFile(args.tokenFile, "utf8")).trim();
} catch (e) {
console.error(`Error reading token file '${args.tokenFile}': ${e.message || e}`);
process.exit(1);
}
const url = `https://api.cloudflare.com/client/v4/zones/${args.zone}/dns_records/${args.record}`;
const payload = {
type: args.rtype,
name: args.name,
content: args.content,
ttl: args.ttl
};
let response;
try {
response = await fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify(payload)
});
} catch (e) {
console.error(`Unexpected error: ${e.message || e}`);
process.exit(1);
}
const body = await response.text();
console.log(body);
let result;
try {
result = JSON.parse(body);
} catch (e) {
console.error(`Failed to parse response: ${e.message || e}`);
process.exit(1);
}
if (!response.ok || !result.success) {
console.error(`Error: ${body}`);
process.exit(1);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment