One of the theoretical benefits from working with Node.js is the possibility to share the same scripts between clients and the server. That would make it possible to degrade the same functionality to the server if the client does not support javascript.
However, the Node.js require()
method works on it's own. In the script you load, you can add stuff to this
or exports
that will later be available in the object that fetched the script:
var stuff = require('stuff');
stuff.show();
In stuff.js:
this.show = function() {
return 'here is my stuff';
}
So, when re-using this script on the client, the .show()
method will be added to the window
scope. That is not what we want here, instead we would like to add it to a custom namespace.
My only solution so far is something like (in stuff.js):
var ns = typeof exports == 'undefined' ? (function() {
return window['stuff'] = {};
})() : exports;
ns.show = function() {
return 'here is my stuff';
}
delete ns; // remove ns from the global scope
This works quite well since I can call stuff.show()
on the server and client. But it looks quirky. I tried searching for solutions but node.js is still very new (even to me) so there are few reliable resources. Does anyone have a better idea on how to solve this?
require
function and load it as a script in the browser that works exactly the same way as it does on node.js – Niccolite