Last active
August 29, 2015 14:02
-
-
Save saintc0d3r/76850088f472eaf6144a to your computer and use it in GitHub Desktop.
Hello World in Express +Swig + MongoDb
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
// Initialise Express | |
var express = require('express'), | |
app = express(); | |
// Initialise Consolidate | |
var consolidate = require('consolidate'); | |
// setup swig as the view html engine | |
app.engine("html", consolidate.swig); | |
app.set("view engine", "html"); | |
// setup views directory | |
app.set("views", __dirname+"/views"); | |
// initialise Mongodb objects | |
var MongoClient = require('mongodb').MongoClient; | |
var ServerInfo = require('mongodb').Server; | |
var mongoclient = new MongoClient(new ServerInfo('localhost', 27017, { "native_parser": true }) ); | |
// Define which mongodb's database we want to work with | |
var db = mongoclient.db('demo'); | |
// Define '/' route: | |
app.get('/', function(request, response){ | |
// Retrieve the document we want to render | |
db.collection('hello_mongodb_express').findOne({}, function(err, result){ | |
if (err) throw err; | |
// render hello.html view page | |
response.render('hello', result); | |
}); | |
}); | |
// Define '404 - Page not found' route | |
app.get('*', function(request, response){ | |
response.send(404, "404 - Page Not Found"); | |
}); | |
// Connect to the mongodb | |
mongoclient.open(function(err, mongoclient){ | |
if (err) throw err; | |
// Had the express instance to listen port 8080 | |
app.listen(8080); | |
console.log('Express server is started on port 8080'); | |
}); |
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
{ | |
"name": "hello_express_swig", | |
"version": "0.0.0", | |
"main": "app.js", | |
"dependencies": { | |
"express": "~4.4.1", | |
"consolidate": "~0.10.0", | |
"swig": "~1.3.2", | |
"mongodb": "~1.4.5" | |
}, | |
"license": "GPL", | |
"author": "Wendy Sanarwanto" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment