One of the benefits of using Node for your web backend is that you can literally reuse the exact same code verbatim on the both the server and in the browser. The first time it happens to you you might feel like you just took a wormhole through the coding space time continuum.
I had a seemingly simple problem that I was reading the most frustrated advice for. All I wanted to do was to use my Javascript object in Node in the browser.
On the server we had an object that looked like this:
module.exports.countries = {
'CA': {
name: 'CANADA',
regions: {
"AB": "ALBERTA",
"BC": "BRITISH COLUMBIA",
"LB": "LABRADOR",
// Skip a few...
"YU": "YUKON"
}
},
'US': {
name: 'UNITED STATES',
regions: {
'AL': 'ALABAMA',
'AK': 'ALASKA',
'AR': 'ARKANSAS',
// Skip a few...
'WY': 'WYOMING'
}
}
};
And I wanted to use this exact same data structure on browser. Ideally the the client side javascript would like like this:
var countries = { /* same as above */ }
/**
* Update region based on selected country.
*/
$('#country').change(function () {
var country = $('#country').val();
var regions = countries[country].regions;
// Populate dropdown with regions...
});
Here's a well asked question in which it was collectively decided to make an Ajax call to get the data. This just seems wrong. Why would you make a second network request to get data that you already had?
All the Ajax call is doing is converting an Javascript object in node to a string on the server, and then an HTTP response to a Javascript object in the browser. We can do that ourselves by calling JSON.stringify or util.inspect and render the Javascript object as is:
// We render in Node as usual.
res.render('my_page', {countries: geo.countries});
//- In Jade, lines beginning with dash (-) are run on the server.
- var countriesJson = JSON.stringify(countries)
// Exclamation point (!) tells Jade not to escape output. Otherwise the quote is escaped as " which is definitely not going to compile in the browser.
var countries = !{countriesJson};
Viola, problem solved.



