I am performing messaging via websockets between a HTML5 client and server running on node.js. Naturally I chose JSON as the message format and as such created common javascript
Take a look at nodeJS modules.
Would be in comm.js:
module.exports = function(/* any dependency? */){
// things
// you can return some object
}
In the files you need comm.js
require('./common/js/comm.js')();
// or you can assign it to a variable if it returned something
Hope that helps!
Have you researched how Node modules work? If you're developing using this pattern, it's fairly simple to use require('./common/js/comms')
on the server while still including it on your client as well.
This article should point you in the right direction: https://caolan.org/posts/writing_for_node_and_the_browser.html
The following is the code that Tyler linked to in his comments below.
The example (example.js):
if(typeof exports == "undefined"){
exports = this;
}
Example = function() {
this.init();
};
Example.prototype = {
init: function() {
console.log('hello world');
}
};
exports.Example = new Example();
The node.js usage of example.js (app.js):
example = require('./example');
The html usage of example.js (index.html):
<html>
<head>
<title></title>
</head>
<body>
<script src="./example.js"></script>
</body>
The change by the OP was to assign exports.Example
to Example
instead of to an new instance. Thus the node.js logic can use the following:
var Example = require('./example.js').Example;
var foo = new Example();
Thus the original question is solved.