This commit is contained in:
sample-text-here 2021-04-09 12:43:20 -07:00
parent 8f0e286891
commit 6d304cdcf3
2 changed files with 45 additions and 0 deletions

View file

@ -3,8 +3,14 @@
a coding challenge i made for myself; how much
can i fit in one hundred lines or less?
i'll try to keep these understandable and not
mangle/minify them. if you want to use them,
you probrably should edit them to your liking
first.
- `server.js` basic http server based off of express
- `templater.js` pre-render your webpages server side
- `data.js` easily extendible database
- `simple.css` css styling for minimal sites
- `chat.js` chat server; connect with netcat. somewhat buggy
- `request.js` async wrapper for http

39
request.js Normal file
View file

@ -0,0 +1,39 @@
const https = require("https");
const stream = require("stream");
async function request(method, url, body, headers = {}) {
return new Promise((resolve, reject) => {
const req = https.request(url, { headers, method }, (res) => {
let data = "";
res.setEncoding("utf8");
res.on("data", (d) => (data += d));
res.on("end", () => resolve(data));
res.on("error", reject);
});
if (body) {
if (body instanceof stream.Readable) {
body.pipe(req);
} else {
req.end(body);
}
}
});
}
async function get(url, headers = {}) {
return request("GET", url, null, headers);
}
async function post(url, body, headers = {}) {
return request("POST", url, body, headers);
}
async function getJSON(url, headers = {}) {
return JSON.parse(await get(url, headers));
}
async function postJSON(url, body, headers = {}) {
return JSON.parse(await get(url, JSON.stringify(body), headers));
}
module.exports = { request, get, post, getJSON, postJSON };