Created
February 7, 2012 05:18
-
-
Save markdaws/1757378 to your computer and use it in GitHub Desktop.
Example of how to share JavaScript between client and node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// common.js ====================================== | |
(function(exports) { | |
// Define all your functions on the exports object | |
exports.foo = function() { | |
return 'bar'; | |
}; | |
})((typeof process === 'undefined' || !process.versions) | |
? window.common = window.common || {} | |
: exports); | |
// ================================================ | |
// clientfile.html ================================== | |
// Using the common code in a browser | |
<html> | |
<head> | |
<script src="common.js"></script> | |
</head> | |
<body> | |
<script> | |
alert(window.common.foo()); | |
</script> | |
</body> | |
</html> | |
// ================================================ | |
// nodefile.js ==================================== | |
// Using the code from a node.js file | |
var common = require('./common'); | |
console.log(common.foo()); | |
// ================================================ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment