Skip to content

Instantly share code, notes, and snippets.

@AnandChowdhary
Last active December 24, 2020 00:36
Show Gist options
  • Save AnandChowdhary/bf1dce1400a6fc86afd1921085feff93 to your computer and use it in GitHub Desktop.
Save AnandChowdhary/bf1dce1400a6fc86afd1921085feff93 to your computer and use it in GitHub Desktop.
Convert a JSON key-value file URL to Netlify _redirects file

JSON KV to Netlify Redirects

Using npx with Node.js, you can run GitHub Gist scripts. This is a script to

Usage

For example, if you have a JSON file in a repo and its URL is https://raw.githubusercontent.com/TwenteMe/data/master/redirects.json, use:

npx https://gist.github.com/AnandChowdhary/bf1dce1400a6fc86afd1921085feff93 https://raw.githubusercontent.com/TwenteMe/data/master/redirects.json

This will generate a _redirects file for server-side redirects on Netlify.

#!/usr/bin/env node
const fs = require("fs");
const http = require("http");
const https = require("https");
const URL = process.argv[process.argv.length - 1];
/**
* getJSON: RESTful GET request returning JSON object(s)
* @param options: http options object
* @param callback: callback to pass the results JSON object(s) back
* @source https://stackoverflow.com/a/9577651/1656944
*/
const getJSON = (url, onResult) => {
const port = url.startsWith("https://") ? https : http;
let output = "";
const req = port.request({
host: URL.split("://")[1].split("/")[0],
path: URL.split("://")[1].replace(URL.split("://")[1].split("/")[0], "")
}, res => {
res.setEncoding("utf8");
res.on("data", chunk => {
output += chunk;
});
res.on("end", () => {
let obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on("error", err => res.send("ERR " + err.message));
req.end();
};
console.log("Fetching file...", URL);
let redirects = "";
getJSON(URL, (statusCode, result) => {
for (const slug in result) {
redirects += `/${slug} ${result[slug]}\n`;
}
fs.writeFileSync("_redirects", redirects);
});
{
"name": "json-to-netlify",
"version": "1.0.0",
"bin": "./index.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment