javascript - NodeJs Require a File -


i using nodejs. possible require javascript file in node in browsers? because when use require() method calls javascript file no access global variables in server.js "use strict" guess. needed load module , make continuation of main file since module depends on global variables.

edit:

i have server.js file:

var settings = require("settings.js"); var clients = require("clients.js"); var removepack = [];  /**here runs websocket server**/ ... ... //when new socket connects: io.on("connection", function(socket){     var socket.id = math.random();     var client = clients.create(socket.id); }); 

here clients.js file:

exports.create = function(){     self.team = settings.generaterandomteam(); /*the problem here. can´t access settings variable*/     self.maxspeed = settings.maxspeed;     ...     ...     return self; } 

edit 2:

when use settings = require("settings.js") following error:

typeerror: settings.generaterandomteam() not function.

my settings.js file this:

settings.generaterandomteam = function(){    //some code }  module.exports = settings; 

thanks!

to access settings object clients.js file, add clients.js file:

const settings = require("settings.js");  exports.create = function(){     self.team = settings.generaterandomteam(); /*the problem here. can´t access settings variable*/     self.maxspeed = settings.maxspeed;     ...     ...     return self; } 

modules in node.js cached 2 require() statements resolve exact same file path return exact same cached module. so, because of caching, same settings object each time call require("settings.js").

this key sharing in node.js. don't think loading once , trying share everywhere. instead, think having each module require() in needs (when possible). promotes independence , reusability of modules tend more stand-alone useful rather depending upon global environment that's been built them.

there are, of course, other ways share data pushing data module in module constructor function or pulling data having module call out other modules when loads retrieve data them. may necessary in cases when module needs given specific instance of (like database handle).


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -