Majid Fouladpour
Majid Fouladpour

Reputation: 30282

Sharing config between node app and client side javascript

I need to have some config object both in the node app and in the browser. Here is the path and the content of the config:

path: [app]/public/js/config.js
content:

var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}

In my html I just add a script element and it works fine:

<script src="/js/config.js"></script>

In node app however I do not seem to have imported the object and I get an empty object:

var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}

What am I doing wrong?

Upvotes: 1

Views: 91

Answers (3)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7749

Replace if block

if(!isBrowser) {
    module.exports = config;
}

to

if(!isBrowser()) {//this isBrowser() function
    module.exports = config;
}

Upvotes: 1

Anthony Kong
Anthony Kong

Reputation: 40884

The code should have been

if(!isBrowser()) {
    module.exports = config;
}

isBrowser is a function here. Since in your version !isBrowser always return false so module.exports = config is never executed.

Upvotes: 1

ghybs
ghybs

Reputation: 53370

Your isBrowser variable is assigned a function, but it is never executed.

Therefore it does not perform any environment detection.

Upvotes: 3

Related Questions