Bring in winston for logging, upgrade to async/await for promises

This commit is contained in:
Jacob Windle 2019-01-26 07:48:38 -05:00
parent 0bc24e975c
commit 771ee83fd4

View File

@ -1,27 +1,39 @@
var net = require('net'); var net = require('net');
var http = require('http'); var http = require('http');
var fs = require('fs'); var fs = require('fs');
var winston = require("winston");
const logger = winston.createLogger({
transports: [
new winston.transports.File({filename: 'proxy.log'})
]
});
class HttpRequest { class HttpRequest {
constructor({attrs}) { constructor(attrs) {
this.attrs = attrs; this.attrs = attrs;
this.logSomething = this.logSomething.bind(this); this.logSomething = this.logSomething.bind(this);
this.forwardRequest = this.forwardRequest.bind(this);
} }
// TODO - not working yet. will come back to this. // TODO - not working yet. will come back to this.
logSomething() { logSomething() {
fs.appendFile("proxy.log", this.attrs, (err) => { logger.log({
console.log("Got an error."); level: 'info',
message: this.attrs
}) })
} }
forwardRequest() {
}
} }
/** /**
* Parse an HTTP request. * Parse an HTTP request.
* @param {String} bytes * @param {String} bytes
*/ */
function parseHttpRequest(bytes) { async function parseHttpRequest(bytes) {
let httpRequestAttrs = {headers: ""}; let httpRequestAttrs = {headers: ""};
bytes.split("\r\n").map((row) => { bytes.split("\r\n").map((row) => {
@ -55,25 +67,30 @@ async function logAndSend(bytes) {
console.log(bytes) console.log(bytes)
} }
var server = net.createServer((socket) => {
socket.on('end', (c) => { function startServer() {
console.log("Client disconnected"); var server = net.createServer((socket) => {
socket.on('end', (c) => {
console.log("Client disconnected");
});
socket.on("data", (c) => {
parseHttpRequest(c.toString())
.then((req) => {
req.logSomething();
})
});
})
server.on('connection', (c) => {
console.log("Client connected!");
}); });
socket.on("data", (c) => {
parseHttpRequest(c.toString()).log(); server.listen(8124, () => {
console.log("Server bound.");
}); });
})
server.on('connection', (c) => { return server;
console.log("Client connected!" + c.read(10)); }
});
server.on("listening", (c) => { startServer();
console.log("LISTENING"); module.exports = [parseHttpRequest];
})
server.listen(8124, () => {
console.log("Server bound.");
})
module.exports = [parseHttpRequest];