Share Constant Values between AngularJS and NodeJS

FacebookTwitterGoogle+PinterestWhatsAppStumbleUponShare

Suppose you have a client-side configuration as an Angular module like this:


angular.module('config', [])
  .constant('configuration', {
    API_END_POINT: 'localhost:3000',
    APP_END_POINT : "localhost:9000",
    "ORIGIN_HOST" : "localhost:3000",
    'ENVIRONMENT' : 'dev'
  });

You’d like to pull these constants into your nodejs environment to keep constants canonical. You don’t want some super-complex module to make things messy.

Simply define a “fake angular” on the server-side, then grab your constants.

/* inside nodejs now */
var CONSTANTS;

angular = {
	module : function() {
		return {
			constant: function(name, constants) {
				CONSTANTS = constants;
			}
		}
	}
}

require("../web/scripts/config.js");
console.log(JSON.stringify(CONSTANTS)); // easy peasy

Thought that might help a few of you struggling with sharing code between Angular and node apps!

FacebookTwitterGoogle+PinterestWhatsAppStumbleUponShare
Posted in AngularJS, NodeJS