Skip to content

Instantly share code, notes, and snippets.

@scott2449
Created February 28, 2011 21:02
Show Gist options
  • Save scott2449/848032 to your computer and use it in GitHub Desktop.
Save scott2449/848032 to your computer and use it in GitHub Desktop.
a node experiment
//server.js
var http = require('http'); //http lib used to build the 'client'
var express = require('express'); //express helps us build the 'server' a bit faster
var app = express.createServer(); //used for serving up the main template and the js model
//app.get('/models/data.js', function(req, res){ res.sendfile(__dirname + '/models/data.js') }) //serve up the model when requested specifically
app.use(express.staticProvider(__dirname + '/models')); //using static provide middleware to serve whole model directory
app.get('/panic', function(req, res){ //perform all this logic when /panic is requested
var options = { host: 'localhost', port: 80, path: '/data.js' }; //for url connection
var req = http.get(options, function(clientRes) { // http get, http.request is the more generic form
var body = "";
clientRes.on('data', function (chunk) { //on each chunk read in the data
body+=chunk;
});
clientRes.on('end', function (){ //at the end, feed the downloaded model into the ejs template
res.render('template.ejs', {
locals:JSON.parse(body)
});
});
});
});
//views/template.ejs
<% if (title) { %>
<h2><%= title %></h2>
<% } %>
//views/layout.ejs
<html>
<head><title>node test</title></head>
<body>
<%- body %>
</body>
<html>
//models/data.js
{ "title": "My Site" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment