Is there a way to share and edit global variables between two javascript node runs?
Adam H pointed me in the right direct. The correct way to do this is in fact child_processes.
Below are the code changes:
The main function file main.js now has:
var cp = require('child_process');
var childDataOne = cp.fork('./dataGenOne.js', [process.argv[2]], { silent: true });
var childDataTwo = cp.fork('./dataGenTwo.js', [process.argv[3]], { silent: true });
childDataOne.stdout.on('data', function(data) {
console.log('parent: ' + data);
compareData(data);
//Here is where the output goes
});
childDataTwo.stdout.on('data', function(data) {
console.log('parent: ' + data);
compareData(data);
//Here is where the output goes
});
Now two other files dataGenOne.js and dataGenTwo.js changed to something like this:
process.stdin.resume();
var passingString = nPingTime + "," + nLastPingNumber;
process.stdout.write(passingString);
To start running we only have to do:
node main.js param1 param2
Instead of running dataGenOne.js and dataGenTwo.js individually.
This correctly allows the child processes to pass data back to the parent process. main.js is listening with stdout.on and the two dataGen child processes are passing the data with stdout.write.
Sharing & modifying a variable between multiple files node.js
Your problem is that when you do var count = require('./main.js').count;
, you get a copy of that number, not a reference. Changing count
does not change the "source".
However, you should have the files export functions. Requiring a file will only run it the first time, but after that it's cached and does not re-run. see docs
Suggestion #1:
// main.js
var count = 1;
var add = require('./add.js');
count = add(count);
// add.js
module.exports = function add(count) {
return count+10;
}
#2:
var count = 1;
var add = function() {
count += 10;
}
add();
#3: Personally i would create a counter module (this is a single instance, but you can easily make it a "class"):
// main.js
var counter = require('./counter.js');
counter.add();
console.log(counter.count);
// counter.js
var Counter = module.exports = {
count: 1,
add: function() {
Counter.count += 10;
},
remove: function() {
Counter.count += 10;
}
}
How do I share a global variable between multiple files?
If you truly want a global variable (not advisable, of course) then you're always 100% free to do
window.globalVar = 0;
in any of your modules.
The more robust solution would of course be to have this global variable sit in some sort of dedicated module, like
globalVar.js
export default {
value: 0
};
and then you could
import globalVal from './globalVar';
globalVal.value = 'whatever';
from any modules needed.
The only risk would be that webpack might duplicate this same "global" value into multiple bundles if you're code splitting, depending on your setup. So separate module would be using their own local copy of this not-so-global variable. EDIT - this isn't true. webpack never did this; that comment was based on a misunderstanding on my part.
how to share variable between more than One file in nodejs
My only guess is you might not have the path to app.js right. This works:
// app.js
var myvar = 1
module.exports = {myvar};
// index.js
var mynewvar =require("./app.js")
console.log(mynewvar.myvar);
Here's a repl.it that shows it works:
https://repl.it/repls/CruelMonstrousArchives
Maybe you're doing something different than this?
Sharing variables across files in node.js without using global variables
app.js
var app = express(),
server = require('http').createServer(app),
socket = require('./socket');
var io = require('socket.io').listen(server);
socket(io)
socket.js
module.exports = function (io) {
io.sockets.on('connection', function(socket) {
// Your code here
});
}
Passing global variable to another controller file in Node.js
I have created a global variable (userEmail) which holds the value of current user.
This is your first problem. There is no such thing as the "current user". There can be multiple users who are all making requests to your http server and whose requests are in process.
You cannot keep request-specific state or user-specific state in global variables. Either add that info state to the req
object for the request so other parts of processing the request can all access it from there (that's what middleware does), add it to a user-session that is tied to a specific user and accessible from any request from that user or pass that state to any function that might need it while processing the response for a specific request.
You cannot put user-specific state into a global variable. Multiple requests from different users will overwrite the global and state will get mixed up between requests from different users.
Separately, this structure:
module.exports = {route, userEmail};
exports the current value of userEmail
at the time the module is initialize (which will be 'not assigned' in your code). As the value of your userEmail
variable changes, the export never changes. So, besides the fact that this isn't the right structure for a request-specific variable (as explained above), you also can't export something like this either.
In your specific situation, it appears you want the userEmail
value to be available for future requests from that user. There are several ways to do that, but I would recommend using express-session
and adding the userEmail
to that user's session object. That session object will then be tied to requests from that specific user (via a sessionID stored in a cookie) and the data in the user's session object will be available with all future request from that user (within the configured time limit of the session cookie).
How to use global variable in node.js?
Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
Nodejs: Global variables across multiple files
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.
Related Topics
Image Taken from Camera Not Saved to Gallery
Onclick JavaScript to Make Browser Go Back to Previous Page
How to Bind on Click Event on Dynamically Created Button in Angular 6
React Jsx - Make Substring in Bold
Detect If a Field Is Updated With JavaScript or Jquery
How to Remove Special Character from Json Without Parsing
How to Prevent Ajax Requests to Follow Redirects Using Jquery
Save State When Refresh Page - Reactjs
Angular 4: How to Read Content of Text File With Httpclient
How to Set Image to Fit Width of the Page Using Jspdf
How to Replace Double/Multiple Slash to Single in Url
How to Show Roles of User Discord.Js/Userinfo Command
How to Find Object in a List of Items by Index Using Es6 (Reactjs)
How to Programmatically Clear/Reset React-Select
Select Value of Input Element Inside HTML Table Using Jquery
How to Pass 3 Parameters in Onclick Function .The Parameters Are Inside PHP Tag
Most Efficient Method to Groupby on an Array of Objects
Remove the Default Browser Header and Footer When Printing HTML