Created
November 13, 2012 06:45
-
-
Save lgsunnyvale/4064359 to your computer and use it in GitHub Desktop.
node json server boilerplate
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 express = require('express'); | |
var app = express(); | |
var http = require("http"); | |
var fs = require("fs"); | |
var cons = require('consolidate') | |
var mu = require('mu2'); | |
var util = require('util'); | |
app.configure(function(){ | |
mu.root = __dirname | |
app.use(express.logger('dev')) | |
app.use(express.static(__dirname)) | |
app.use(express.bodyParser()) | |
app.use(express.methodOverride()) | |
app.use(express.cookieParser("secret")) | |
app.use(express.session({ secret: 'keyboard cat' })) | |
app.use(app.router) | |
}); | |
app.init = function(callback){ | |
fs.readFile('./sample.json', 'utf8', function(error, data) { | |
if (error) { | |
throw(error); | |
} | |
else | |
app.set("json", data); | |
callback(); | |
}) | |
}; | |
app.get('/things', function(req, res){ | |
res.set('Content-Type', 'text/json'); | |
res.send(app.get("json")); | |
}); | |
app.get('/things/:id', function(req, res){ | |
res.set('Content-Type', 'text/json'); | |
res.send((JSON.parse(app.get("json")))[req.param('id')]); | |
}); | |
app.get('/main', function(req, res){ | |
var firstThing = JSON.parse(app.get("json"))["0"]; | |
var stream = mu.compileAndRender('main.html', firstThing); | |
util.pump(stream, res); | |
}); | |
app.init(function() { | |
app.listen(3000); | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment