when I load a static html page I want to send a JS Object to that page (which is data that comes from mongo). I can accomplish this with a Socket emit, but that seems like overkill. I also know I can write the whole document using JS, but I want to leverage HTML for the bulk of the page as it makes things easier for people I work with.
It would be nice if I could inject html into my static page before it gets sent out by the server, but I don’t think this is possible. I’ll settle with an html page that has either a function to parse data sent to the page at “load” time, etc..
My current samples are bogus or I’d send them along. Thanks for looking at my
question!
** current snippet, for fun **
function createServer(req, res) {
var path = url.parse(req.url).pathname;
var fsCallback = function(error, data, cb) {
if(error) throw error;
res.writeHead(200);
res.write(data);
res.end();
if(cb) cb();
}
switch(path) {
case '/subpage':
case '/subpage.html':
doc = fs.readFile(__dirname + '/subpage.html', function(error, data) {
fsCallback(error, data, function() {
var db = new mongo.Db('mydb', new mongo.Server('localhost', '27017', {}), {});
db.open(function() {
db.collection('mytable', function(error, collection) {
collection.find(function (error, cursor) {
//store some data and send it to the page -- that will happen somewhere around here?
});
});
});
});
});
break;
default:
doc = fs.readFile(__dirname + '/index.html', fsCallback);
break;
}
}
I’ve had great results with Express and the JADE templating engine.
I find that JADE makes hand-crafted HTML much cleaner and less bulky, even if most of the page is static. And, inserting dynamic data is obviously supported. JADE is simple and elegant with a very straightforward mapping between template syntax and generated HTML. With the indentation driving hierarchy versus more fragile XML tags, and minus the verbosity of all the closing tags, I have found JADE to be quicker to write and significantly more maintainable.
For example
versus
if you really want to keep your existing static HTML file, narrowly solving your asked problem is pretty easy. There’s absolutely no reason you need to spit out the HTML file before the DB data comes back (unless you deliberately want the data populated async to mask DB latency).
Transforming your existing code sample:
But it could still be a lot nicer. If we update the code to follow a few best practices:
Best Practices Code Sample:
server.js
views/subpage.ejs:
views/row.jade: