Imdaniel
Imdaniel

Reputation: 21

Run browser JS in Node.js

I wrote some basic javascript code in AngularJs. I want to be able to run this code in Node.js but keep the possibility to run it in the browser depending the situation.

I know that it is possible do run Node.js code in the browser by using browserify or lobrow but I did not find a solution to run browser code in Node.js

Thanks in advance for your answers

Daniel

Upvotes: 0

Views: 1929

Answers (1)

Wainage
Wainage

Reputation: 5412

First a warning. NO DOM manipulation in your module since node has no DOM. Also if you need to require anything in your module you really should be looking at Browserify et al.

Your module would look like this

(function(){
    var sayHello = function(name) {
       return "Hello " + name;
    };

    // here's the interesting part
    if (typeof module !== 'undefined' && module.exports) {  // we're in NodeJS
        module.exports = sayHello;
    } else {                                                // we're in a browser
        window.sayHello = sayHello;
    }

})();

In node

var sayHello = require('./myModule');
console.log(sayHello("Node"));        // => "Hello Node"

and in your browser

<script src="myModule.js"></script>
<script>
  console.log(sayHello("Browser"));   // => "Hello Browser"
</script>

Upvotes: 1

Related Questions