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

Asked

Viewed 1,007 times

1

I am creating my first application with nodejs and have a question in javascript. In the code below I am reading a sensor and saving in 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;
  });
});

1 answer

1

You need to create a way to communicate between files. O require is requested once per module and stays 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"

  });
});

B file (sensor.js)

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

module.exports = function(){
    return valor;
}
  • Sergio thanks for the help, but in that case I would have to pass the value variable from file A to file B. If you re-turn the value variable in file A and require in file B, it will work?

  • @Giovanezanon can explain what the variable is, if it is A that wants to inform B pu if it is B that needs to fetch A?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.