Created
October 11, 2016 03:09
-
-
Save v3rse/d4c3d43fbe29751f58ca9407c5a5b9c3 to your computer and use it in GitHub Desktop.
A simple json file based database server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var url = require('url'); | |
var fs = require('fs'); | |
var DB_FILE = 'database.json'; | |
function init(){ | |
//create file if it's present. | |
//synchronous because it needs to happen before requests can be processed | |
if(!fs.existsSync(DB_FILE)){ | |
console.log(`Initialising storage.\n -Creating ${DB_FILE} file`); | |
fs.writeFileSync(DB_FILE,"{}"); | |
} | |
} | |
function readFromFile(callback){ | |
fs.readFile(DB_FILE,'utf-8',callback); | |
} | |
function writeToFile(data,callback) { | |
fs.writeFile(DB_FILE,data,callback); | |
} | |
function getData(callback){ | |
readFromFile(callback); | |
} | |
function setData(data,callback) { | |
//parse object to json string | |
var dataString = JSON.stringify(data); | |
writeToFile(dataString,callback) | |
} | |
http.createServer(function(req, res){ | |
//use querystring module on query strings and stores in 'query' object | |
var parseUrl = url.parse(req.url, true, true); | |
var statusCode = 404; | |
var content = "404 - Not Found" | |
//simple routing | |
if(parseUrl.pathname === "/set"){ | |
console.log("Inserting value into database:",parseUrl.query); | |
statusCode = 200; | |
//retrieve current state of file (async) | |
getData(function(err,dataString){ | |
if(err) | |
throw err; | |
//parse json string | |
var data = JSON.parse(dataString); | |
//assign new query object's contents. don't forget previous state of 'data' | |
Object.assign(data,parseUrl.query,data); | |
//persist data in file (async) | |
setData(data, function(err){ | |
if(err) | |
throw err; | |
content = "Data inserted"; | |
res.writeHead(statusCode,{"Content-Type":"text/plain"}); | |
res.end(content); | |
}); | |
}); | |
}else if(parseUrl.pathname === "/get"){ | |
var searchKey = parseUrl.query.key; | |
console.log("Retrieving value from database: key="+searchKey); | |
statusCode = 200; | |
//get search key | |
getData(function(err, dataString){ | |
var data = JSON.parse(dataString); | |
content = data[searchKey]; | |
res.writeHead(statusCode,{"Content-Type":"text/plain"}); | |
res.end(content); | |
}); | |
}else{ | |
res.writeHead(statusCode,{"Content-Type":"text/plain"}); | |
res.end(content); | |
} | |
}).listen(4000); | |
//file initialiser | |
init(); | |
console.log("Started DB server..."); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment