I'm sure this is a simple syntax thing that I'm just not getting but here's my code. The purpose of which is to have an object that is shared between two other scripts.
The object saved as canStat.js
class cCan {
constructor() {
this.tmp = 0;
this.hum = 0;
this.isRelay1 = false;
this.isRelay2 = false;
this.isRelay3 = false;
this.isRelay4 = false;
}
}
module.exports = cCan;
next door to that file I have a script listening for data to be received, server.js
which it is successfully over UDP, that should be saved to that object as follows.
const dgram = require('dgram');
const listener = dgram.createSocket('udp4');
const cCan = require('./canStat');
var ceres1 = new cCan();
listener.on('message', (msg, rinfo) => {
if (msg.readUInt8(0) == 1 ) {
console.log("Received Packet");
console.log("IP: ", `${rinfo.address}`);
console.log("Port: ", `${rinfo.port}`);
console.log("Byte Size: ", `${rinfo.size}`);
console.log("Humidity: ", msg.readUInt8(2), "%");
console.log("Temperature: ", msg.readUInt8(1), "C");
ceres1.tmp = msg.readUInt8(1);
ceres1.hum = msg.readUInt8(2);
if (msg.readUInt8(3) == 0) {
ceres1.isRelay1 = true;
console.log("Cooler Relay is On");
} else {
ceres1.isRelay1 = false;
console.log("Cooler Relay is Off")
}
if (msg.readUInt8(4) == 0) {
ceres1.isRelay2 = true;
console.log("Humidifier Relay is On");
} else {
ceres1.isRelay2 = false;
console.log("Humidifier Relay is Off")
}
if (msg.readUInt8(5) == 0) {
ceres1.isRelay3 = true;
console.log("Fan Relay is On");
} else {
ceres1.isRelay3 = false;
console.log("Fan Relay is Off")
}
if (msg.readUInt8(6) == 0) {
ceres1.isRelay4 = true;
console.log("Lighting Relay is On");
} else {
ceres1.isRelay4 = false;
console.log("Lighting Relay is Off")
}
console.log(
ceres1.tmp,
ceres1.hum,
ceres1.isRelay1,
ceres1.isRelay2,
ceres1.isRelay3,
ceres1.isRelay4
);
}
});
module.exports = ceres1;
Two folders down from these two (within the master "app" folder) is located (app/api/routes/test.js
), test.js
var ceres1 = require('../../server');
// Get data
function getData() {
console.log(
ceres1.tmp,
ceres1.hum,
ceres1.isRelay1,
ceres1.isRelay2,
ceres1.isRelay3,
ceres1.isRelay4
);
}
getData();
However this is doesn't appear to be saving to a common class object and is returning the constructor function values (0, 0, false, false, false, false), where as the first console.log in the server.js
reports that the values are being saved to the object ceres1
.
What do I have to do to have to have these two scripts, server.js
& test.js
, to share the same class object? Thanks!