javascript - Clean way to "require" in nodejs when having to pass params -


i got files called socket.js , chat.js.

let's chat.js contains:

function chat(io, socket) {   this.sendchatmessage(data) {}; } module.exports = chat; 

and socket.js

module.exports = function (io) {     io.on('connection', function(socket) {       var chat = new (require('./chat'))(io, socket),     }); } 

after several tries, above cleanliest way of requiring "chat" i've found, still looks weird used.

i tried stuff (still clean guess)

var chat = require('./chat'),     chat = new chat(io, socket); 

also tried adding "new" in module.exports = new chat; directly etc. etc.

is there standard this? if not, use?

yup, that's how it: export whatever function(s) need , call them after requiring module.

also tried adding "new" in module.exports = new chat

don't unless want export instance , not constructor.

it's pretty common use pattern omit new call constructor:

function chat(io, socket) {   if (! (this instanceof chat)) return new chat(io, socket);   this.sendchatmessage(data) {}; } 
var chat = require('./chat')(io, socket) 

Comments