Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active August 29, 2015 14:16
Show Gist options
  • Save karenpeng/3abc0be110cd00e380b1 to your computer and use it in GitHub Desktop.
Save karenpeng/3abc0be110cd00e380b1 to your computer and use it in GitHub Desktop.
// When your server receives a request on
// http://localhost:4000/set?somekey=somevalue
// it should store the passed key and value in memory.
// When it receives a request on
// http://localhost:4000/get?key=somekey
// it should return the value stored at somekey.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var port = 4000;
server.listen(4000);
var fs = require('fs');
var database = {};
//in case server shuts down or something
try {
database = JSON.parse(fs.readFileSync('database.json').toString());
} catch (e) {
console.log('no database yet');
}
app.get('/', function (req, res) {
res.send('hello world');
});
app.get('/set', function (req, res, next) {
var logs = [];
for (var key in req.query) {
//database[key] the key is a variable holding some value
//database.key the key is literarily key, you put a key property to database :(
database[key] = req.query[key];
//console.log(key, req.query[key]);
logs.push('data saved as: { ' + key + ':' + req.query[key] + '}');
}
fs.writeFile('database.json', JSON.stringify(database), function (err) {
if (err) return next(err);
console.log('saved data to file');
res.end(logs.join('\n'));
});
});
app.get('/get', function (req, res, next) {
//read file
fs.readFile('database.json', function (err, data) {
if (err) return next(err);
var data;
try {
data = JSON.parse(data.toString());
if (data[req.query.key] !== undefined) {
res.send(database[req.query.key]);
} else {
res.send('ooops no such record :(');
}
} catch (e) {
return next(e);
}
});
// just read from memory
// if (database[req.query.key] !== undefined) {
// res.send(database[req.query.key]);
// } else {
// res.send('ooops no such record :(');
// }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment