Skip to content

Instantly share code, notes, and snippets.

@labiak
Created November 7, 2018 17:41
Show Gist options
  • Save labiak/8b55a9f9a11ceb8b4e8d314132fff936 to your computer and use it in GitHub Desktop.
Save labiak/8b55a9f9a11ceb8b4e8d314132fff936 to your computer and use it in GitHub Desktop.
const http = require('http');
const {getOptions, pretty} = require('./utilities');
const [{port = 1989, help = false, color = false}] = getOptions();
function report(...args) {
console.log('// ', ...args);
}
if (help) {
console.log('script expose --color --port=8080');
process.exit();
}
const server = http.createServer(function(req, res) {
data = [];
req.on('data', c => data.push(c));
req.on('end', function() {
res.writeHead(200, 'Accepted', {
'content-type': 'application/json'
});
const r = {
url: req.url,
method: req.method,
ip: req.connection.remoteAddress,
headers: req.headers
};
if (data.length > 0) {
r.body = JSON.parse(data.join(''));
}
console.log(color ? r : pretty(r));
res.end(JSON.stringify(r));
});
});
server.listen(+port, function() {
report(`Listen at http://localhost:${port}/`);
});
/**
* @author Taras Labiak <[email protected]>
*/
const path = require("path");
const fs = require("fs");
const NODE_PRODUCTION_MODE = "production";
const DEBUG = NODE_PRODUCTION_MODE !== process.env.NODE_ENV;
/**
*
* @param object
* @returns {string}
*/
function pretty(object) {
return DEBUG ? JSON.stringify(object, null, " ") : JSON.stringify(object);
}
function consequence(...functions) {
const seq = function sequence(...args) {
const local = sequence.functions;
const last = local.length - 1;
for (let i = 0; i < last; i++) {
const a = functions[i].call(this, ...args);
if (undefined !== a) {
args = a;
}
}
return functions[last].call(this, ...args);
};
seq.functions = functions;
return seq;
}
function aspect(base, event, fun) {
if ("function" === typeof event) {
fun = event;
} else {
const _fun = fun;
fun = function(e, ...args) {
if (event === e) {
_fun(...args);
}
};
}
base.aspect =
"function" === typeof base.aspect ? consequence(fun, base.aspect) : fun;
}
/**
*
* @param reader
* @param {string} type
* @param {string} encoding
* @returns {Promise<Object>}
*/
function read(reader = process.stdin, ...args) {
return read[type](reader, ...args);
}
/**
* @param {Stream} reader
* @returns {Promise<Buffer>}
*/
read.buffer = function buffer(reader = process.stdin) {
return new Promise(function(resolve, reject) {
const chunks = [];
read.aspect("start", reader, chunks);
reader.on("data", function(chunk) {
read.aspect("data", reader, chunk, ...chunks);
chunks.push(chunk);
});
reader.on("error", function(error) {
read.aspect("error", reader, error);
reject(error);
});
reader.on("end", function() {
read.aspect("end", reader, chunks);
const buffer =
chunks.length > 1
? "string" === typeof chunks[0]
? chunks.join("")
: Buffer.concat(chunks)
: chunks[0];
read.aspect("buffer", reader, buffer);
resolve(buffer);
});
});
};
/**
* @param {Stream} reader
* @param {string} encoding
* @returns {Promise<string>}
*/
read.string = async function string(reader = process.stdin, encoding = "utf8") {
if ("string" === typeof reader) {
reader = fs.createReadStream(reader, { encoding });
}
const buffer = await read.buffer(reader);
const string = buffer.toString(encoding);
read.aspect("string", string);
return string;
};
/**
* @param {Stream} reader
* @param {string} encoding
* @returns {Promise<string>}
*/
read.json = async function json(reader = process.stdin, encoding = "utf8") {
const string = await read.string(reader, encoding);
const json = JSON.parse(string);
read.aspect("json", json);
return json;
};
read.config = {
max: 10 * 1024 * 1024
};
aspect(read, "data", function(reader, ...chunks) {
if (chunks.reduce((acc, chunk) => acc + chunk.length, 0) > read.config.max) {
const error = new Error(
`File is large than ${read.config.max / (1024 * 1024)} MB`
);
reader.destroy(error);
throw error;
}
});
function getProcessArguments(args = process.argv) {
const index = args.map(a => path.basename(a)).indexOf("node");
return args.slice(index + 2);
}
function getOptions(args = process.argv, options = {}) {
const ordered = [];
for (const arg of getProcessArguments(args)) {
if (arg.indexOf("--") === 0) {
const p = arg.split("=");
options[p[0].slice(2)] = 2 === p.length ? p[1] : true;
} else {
ordered.push(arg);
}
}
return [options, ...ordered];
}
function breakpoint() {
debugger;
}
function print(...args) {
console.log(...args);
}
function warn(...args) {
console.warn("WARNING: ", ...args);
}
function cry(...args) {
console.error("CRY: ", ...args);
}
function die(message) {
console.error(message);
process.exit(1);
}
module.exports = {
breakpoint,
cry,
die,
getProcessArguments,
getOptions,
pretty,
print,
read,
warn
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment