Share Variables Between Files in Node.Js

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 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

});
}

How to share a variable between two files generated by a function

Your current code is particularly problematic.
return dir; occurs before fs.access/fs.readFile finishes. These are asynchronous functions and require the use of callback, promise, or async/await styled coding. The gist of it is that the code continues executing other code while it waits on I/O (such as reading a file) and the way you have written it causes nothing to be returned. See https://repl.it/@CodyGeisler/readFileCallback for a working callback example.

workingDirectory: () => {
let dir;
fs.access(`${homeDir}/.unitv`, fs.constants.F_OK, (err) => {
if(err) throw err;
fs.readFile(`${homeDir}/.unitv`, 'utf8', (readErr, data) => {
if(readErr) throw readErr;
let jsonData = JSON.parse(data);
dir = jsonData.WorkingDirectory;
});
});
return dir;
}


Related Topics



Leave a reply



Submit