Javascript:在脚本之间共享类对象

时间:2018-12-12 22:06:58

标签: javascript import global-variables

我确定这是一个简单的语法问题,只是我没有得到,但这是我的代码。目的是要有一个在其他两个脚本之间共享的对象。

对象另存为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;

该文件的隔壁,我有一个脚本,用于监听要通过UDP成功接收的数据server.js,该脚本应按如下方式保存到该对象中。

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;

位于这两个文件夹下面的两个文件夹(在主“ app”文件夹中)位于(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();

但是,这似乎并没有保存到公共类对象中,而是返回了构造函数的值(0、0,false,false,false,false),其中{{ 1}}报告值已保存到对象server.js

要拥有两个ceres1server.js脚本来共享同一个类对象,我该怎么办?谢谢!

0 个答案:

没有答案