How to use the contents of a javascript variable in another js file?

1

I'm creating my first application with nodejs and I have a question in javascript. In the code below I'm reading a sensor and saving in the variable value every 30 seconds, I wonder if I can use this variable and its value in another js file? How would this be done?

var five = require("johnny-five"),
  board, potentiometer;

board = new five.Board();


board.on("ready", function() {

  potentiometer = new five.Sensor({
    pin: "A2",
    freq: 30000
  });

  board.repl.inject({
    pot: potentiometer
  });

  potentiometer.on("data", function() {
      var valor = this.value;
  });
});
    
asked by anonymous 06.01.2017 / 19:17

1 answer

1

You need to create a way to communicate between files. The require is requested once per module and is in memory. If you pass a function then you have the door open to go searching, or pushing new values.

It could be something like this:

File A:

var five = require("johnny-five");
var sensor = require('./sensor'); // um ficheiro sensor.js na mesma diretoria

var board, potentiometer;
board = new five.Board();


board.on("ready", function() {

  potentiometer = new five.Sensor({
    pin: "A2",
    freq: 30000
  });

  board.repl.inject({
    pot: potentiometer
  });

  potentiometer.on("data", function() {
      var valor = this.value;
      var sensorValue = sensor(); // <--- aqui vais buscar o valor de "sensor"

  });
});

File B (sensor.js)

var valor = 0;
setInterval(function(){
    valor = Math.random() * 100; // valor muda a cada 0.5 segundos
}, 500);

module.exports = function(){
    return valor;
}
    
06.01.2017 / 20:05