How can I share code between Node.js and the browser?
If you want to write a module that can be used both client side and server side, I have a short blog post on a quick and easy method: Writing for Node.js and the browser, essentially the following (where this
is the same as window
):
(function(exports){
// Your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
Alternatively there are some projects aiming to implement the Node.js API on the client side, such as Marak's gemini.
You might also be interested in DNode, which lets you expose a JavaScript function so that it can be called from another machine using a simple JSON-based network protocol.
Sharing Code between Node.js and the browser
You need something like this:
function someFunctionName() {
// Common functional
if (typeof module !== 'undefined' && module.exports) {
// Do something only in Node.JS
} else {
// Do something else in the browser
}
// Common functional
}
Sharing a class between Node.js and the browser
NowJS is a pretty elegant way to share variables and functions between client JS and Node JS through an automatically sync'ed shared namespace.
There's also dnode, which the author comments on in response to a posting about NowJS here: http://news.ycombinator.com/item?id=2316079
Related Topics
Onchange Event Using React Js for Drop Down
When Is the Body of a Promise Executed
Check If an Element Is Present in an Array
Scrolling an Iframe with JavaScript
Make Several Requests to an API That Can Only Handle 20 Request a Minute
Rails - Could Not Find a JavaScript Runtime
Difference Between Using Bracket ('[]') and Dot ('.') Notation
What Does the @ Mean Inside an Import Path
JavaScript Event Handler with Parameters
Programmatically Open New Pages on Tabs
Invoking a Function Without Parentheses
$(Document).Ready(Function(){}); VS Script at the Bottom of Page
JavaScript - Populate Drop Down List with Array
Differencebetween Substr and Substring
How to Check in JavaScript If One Element Is Contained Within Another
How to Get a Url Parameter in Express
How to Use Redirect in Version 5 of React-Router-Dom of Reactjs