Reputation: 414
Using node.js I try to read every second the result of a variable from an other file.
This variable is constantly updated with a websocket stream.
In my socket.js file the variable is updated:
let updatedVariable = 0;
const ws = new WebSocket('wss://stream.com.....');
ws.on('message', function incoming(data) {
updatedVariable = data;
});
export default {ws, updatedVariable}
In my file index.js I try to read the variable every second:
import socket from './socket.js';
setInterval(tick, 1000);
const tick = () => {
console.log(socket.updatedVariable);
}
How can I access the updated variable "updatedVariable" every second in my file index.js ?
Upvotes: 0
Views: 134
Reputation: 664599
Do not use an object literal in a default export. You never modify the object properties, only the local variable.
Instead, just export the variables themselves:
// socket.js
export let updatedVariable = 0; /*
^^^^^^ */
export const ws = new WebSocket('wss://stream.com.....'); /*
^^^^^^ */
ws.on('message', function incoming(data) {
updatedVariable = data;
});
// index.js
import * as socket from './socket.js';
// ^^^^^^^^^^^
setInterval(() => {
console.log(socket.updatedVariable);
}, 1000);
(Not endorsing the usage of mutable exports. It is an antipattern because it encourages global state. But still, the above works and is the simplest way to fix your code with the chosen approach)
Upvotes: 1