Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common module in node.js and browser javascript

I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.

An example module would be circle.js:

var PI = Math.PI;  exports.area = function (r) {   return PI * r * r; };  exports.circumference = function (r) {   return 2 * PI * r; }; 

and you do a simple

var circle = require('./circle') 

to use it in node.

How could I use that same file in the web directory for my client side javascript?

like image 666
RobKohr Avatar asked Sep 06 '11 23:09

RobKohr


People also ask

What is a module in Node.js the same as in JavaScript?

What is a Module in Node.js? Consider modules to be the same as JavaScript libraries. A set of functions you want to include in your application.

Does Node.js have the same objects as browser based js?

Both the browser and Node. js use JavaScript as their programming language. Building apps that run in the browser is a completely different thing than building a Node. js application.

How JavaScript works in browser and node?

The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute. In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it.

What is CommonJS module?

Getting Started. From a structure perspective, a CommonJS module is a reusable piece of JavaScript that exports specific objects made available to any dependent code. Unlike AMD, there are typically no function wrappers around such modules (so we won't see define here, for example).


2 Answers

This seems to be how to make a module something you can use on the client side.

https://caolan.org/posts/writing_for_node_and_the_browser.html

mymodule.js:

(function(exports){      // your code goes here     exports.test = function(){         return 'hello world'     };  })(typeof exports === 'undefined'? this['mymodule']={}: exports); 

And then to use the module on the client:

<script src="mymodule.js"></script> <script>     alert(mymodule.test()); </script> 

This code would work in node:

var mymodule = require('./mymodule'); 
like image 200
RobKohr Avatar answered Oct 04 '22 04:10

RobKohr


Browserify

Browserify

It magically lets you do that.

like image 26
generalhenry Avatar answered Oct 04 '22 04:10

generalhenry