Skip to content

Instantly share code, notes, and snippets.

@georgio
Last active November 1, 2018 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgio/3b3186ef1be63591fcfe52dc0731aeca to your computer and use it in GitHub Desktop.
Save georgio/3b3186ef1be63591fcfe52dc0731aeca to your computer and use it in GitHub Desktop.
Recurse Application
const http = require('http');
const url = require('url');
//Database
let database = [];
http.createServer((req, res) => {
//Parsing query from URL
let data = url.parse(req.url);
//set method; takes 2 parameters key and value; response includes web page to confirm transaction;
if (req.method === 'GET' && data.pathname === '/set'&& data.query.split('=').length === 2) {
let key = data.query.split('=')[0];
let value = data.query.split('=')[1];
database.push({
key,
value
});
key = value = data = "";
console.log(database);
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write("<h1>Added " + JSON.stringify(database[database.length - 1]) + ". </h1>");
res.end();
}
//get method takes 1 parameter: key and looks up a matching value in the database; response includes web page to confirm transaction
//if value is undefined then no value is available for given key.
else if (req.method === 'GET' && data.pathname === '/get' && data.query.split('=').length === 1) {
let value;
for (let i = 0; i < database.length; i++) {
if (database[i].key == data.query) {
value = database[i].value;
}
}
console.log(value);
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write("<h1>Key: " + data.query + "<br>Value: " + value + " </h1>");
res.end();
//Unsupported requests go through here
} else {
res.statusCode = 404;
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write("<h1>Bad Request.</h1>");
res.end();
}
}).listen(4000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment