vendredi 20 février 2015

How to expose a JS Node Module


I am diving into Node.js and have had success installing express and socket. I was able to make the basic chat program easily. This requires these steps:


In app.js (my Node server)



var server = require('http').Server(app);
var io = require('socket.io')(server);


I included minified socket.io.js file in public/javascripts


In public/javascripts/testchat.js simply call IO like this:



var socket = io();


Then do whatever you want with IO stuff.




I've made my own Node.js module but I don't understand how to expose it.


In node_modules/myModule/index.js



module.exports = require('./lib');


In node_modules/myModule/lib/index.js



module.exports = myModule;

function myModule(){
this.name = "hello";
}

myModule.prototype.test = function(){
console.log(this.name);
}


I can call this stuff easily in app.js



var myModule = require('myModule');
var myMod = new myModule.test(); //hello


But I don't want this thing to run every time I start the server. I want to to only run when a user accesses a specific page. How do I get from here to there? I know I am missing something... I was expecting to be able to do this:


In public/javascripts/myModule.js



var myModule = myModule(); //myModule is undefined
myModule.test();


Thank you.





Aucun commentaire:

Enregistrer un commentaire