NodeJS - Get variable from another file without redefining it each call? - javascript

So I have 2 files a mapgen.js and a main.js. In mapgen.js there is a function that generates a giant 2d array. I want to use this aray in main.js but don't want the function that generates the map to run everytime its 'required' in main.js. I also want to be able to edit the map array eventually.
Example: (not real code just wrote some crap to show what the issue is)
mapgen.js:
var map;
function mapGen(){
//make the map here
this function takes like 2 seconds and some decent CPU power, so
don't want it to ever run more than once per server launch
map = map contents!
}
main.js
var map = require mapgen.js;
console.log(map.map);
//start using map variable defined earlier, but want to use it without
having to the run the big funciton again, since it's already defined.
I know i have to module.exports somewhere but I dont think that will solve my problem still. I would write it to a file but is that not much slower to read and edit than keeping it in the ram? Previously I had gotten past this by keeping everything in 1 file but now I need to clean it all up.

Requiring the module won't automatically invoke the function. You can do that in the main.js file.
mapgen.js
module.exports = function mapGen() {
return [/* hundreds of items here. */];
};
main.js
// Require the module that constructs the array.
const mapGen = require('./mapgen');
// Construct the array by invoking the mapGen function and
// store a reference to it in 'map'.
const map = mapGen(); // `map` is now a reference to the returned array.
// Do whatever you want with 'map'.
console.log(map[0]); // Logs the first element.

I'm not an expert but if you put one condition in mapgen.js that don't work ?
var map;
function mapGen(){
if(!map){
//your code here
map = map contents!
}
}
Combine that with global variable and/or module.exports See
How to use global variable in node.js?

Related

Is it possible to move an array out of the main js file and import it in?

I have a js file that is mostly static. I do not change it at all except one array of values.
Is it possible to move that array out of the main js file and import it in?
Here is my js now:
sw.js:
// array that changes often
const assets = ['/','index.html','long','list','of','assets'];
// lot of code that rarely changes here
Here is what I want to do:
sw.js:
// array that changes often
const assets = require("assets.js");
// lot of code that rarely changes here
assets.js:
const assets = ['/','index.html','long','list','of','assets'];
And please let me know if I have to use ES5 or ES6 to do it.
Related:
Offline Service Worker
https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers
The answer is yes, it's possible. Make sure your declared assets variable is not inside the function so that you can access it globally.
e.g
<script src="assets.js"><script> //declare const assets = ['/','index.html','long','list','of','assets']; here
<script src="sw.js"><script> // you can access the variable *assets* from here.

Require module in Node JS

I used Node JS for web application development. I have a confusion in require() module. I am requiring a JS file located in file_handler directory.
What is the difference between both of the following?
// in server.js
var chat = require("./file_handler/chat.js"); // Does not work
OR
var chat = require("./file_handler/chat.js")(); // It works
Why is the extra parenthesis in the last of the statement?
In the first line the exported function is assigned to chat variable so then you can call it like next like chat();
In the second one the return of exported function is returned to chat variable.
It is actually based on what you export in your module. If you export the object you need, you can just directly do require('module'). If you export a function which returns the object you need, you have to execute that exported function require('module')() to get the desired object.
Read the documentation https://nodejs.org/api/modules.html

How do you modify a nodejs module variable?

(This is probably a very silly question since I'm just beginning with nodejs, nevertheless I can't understand how this works. Let me know what is missing in my question, I'll correct.)
I'm trying to use the npm package likely.
in my server.js file I have thus written this
var Recommender = require('likely');
in likely.js you can find variables like these:
var DESCENT_STEPS = 5000; // number of iterations to execute gradient descent
var ALPHA = 0.0005; // learning rate, should be small
I would like to modify these variables inside my server.js file.
I believe the way to do that is adding this after the require()
Recommender.DESCENT_STEPS = 9999999999;
but that doesn't seem to change the value that is defined in likely.js and that is actually used by the model. (by running the model I can see it doesn't work since so much steps should take forever and the processing time doesn't change at all)
Can I only do this by modifying likely.js?
You cannot modify them programmatically because likely.js only uses the local variable values instead of the current value of the exported versions of the same variables. So if you wanted to change those values you currently would need to edit likely.js. You might want to submit a pull request to that project's repository that makes the code use the exported value (e.g. module.exports.DESCENT_STEPS) instead.
You need to publicize these variables to be viewable by server.js.
var object = {
DESCENT_STEPS = 5000;
ALPHA = 0.0005;
}
module.exports = object;
Now it can be viewed and modified in server.js.
Recommender.ALPHA = 'new value';

How do I update the values of this variable between modules?

So I have module "bot.js" and in this module, it constantly checks for messages and assigns them to a variable (db_users). Since I run my app from "app.js", and I pass the functions that continuously populates db_users, how do I get this information to "app.js"?
Bot.js is using an IRC function that stores user's messages.
var db_users = []
// I then populate db_users with the previous data that is already in mongodb
// using a .find().exec() mongodb command.
bot.addListener('message', function (from, to, text) {
userInfo.checkForUser(db_users);
// checkForUser basically looks through the variable db_users to see if
// there is a username that matches the "from" parameter in the listener
// If it's not there, push some user information into the db_users array
// and create a new MongoDB record.
}
So I have all this, but my main app is a website that can control this "bot" (It's not a spam bot, but a moderation/statistical bot), and I'm using a require function to use "./bot.js" in "app.js"
app.js
bot = require('./bot');
So how would I constantly use the data in bot.js, in app.js? I'm a little fuzzy on how modules work.
Yeah I could just put all of the contents of app.js in bot.js, but it would be too annoying to look through.
Thanks!
Put db_users inside an object so that it's just a reference. Make changes to that reference instead. Then export that outer object. Now since db_users is just a reference, it'll always be a latest copy of whatever it refers to.
bot.js
var data = module.exports = {};
data.db_users = [];
bot.addListener('message', function (from, to, text) {
userInfo.checkForUser(data.db_users);
}
app.js
botData = require('./bot');
botData.db_users will always have the whatever latest changes were made to data.db_users in bot.js

Nodejs: Global variables across multiple files

I have written my code across several files for my node server.
If I have a file, say basket.js:
var Basket = {
fruits : 0,
addFruit : function() {
fruits++;
},
removeFruit : function() {
fruits--;
},
printFruit : function() {
console.log(this.fruits);
}
}
module.export = Basket;
And I have another file called give.js:
var Basket1 = require("./basket.js");
Basket1.addFruit();
Basket1.printFruit();
And another file called take.js:
var Basket2 = require("./basket.js");
Basket2.removeFruit();
Basket2.printFruit();
Will both files write into the same instance of Basket?
In other words, will they both have control over the property, fruits?
Does node manage race conditions on its own? i.e. if two commands to modify fruit come in at the same time from add and sub, does node know how to handle it?
If I want to make a way in which two files can look at a singleton at the same time and access it, is this the way to go?? Or how else does one do it?
Yes, they will access the same object.
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
– Modules docs
No, node does not manage race conditions on its own, because race conditions will not be caused by node itself. Node is single-threaded and thus no code can be executed at the same time as other code. See for example this answer for some more explanation.
I'm a beginner but I think the correct syntax is module.exports not modules.export - if you may correct so that people don't wonder why it does not work like I just did :)

Categories

Resources