0

Im new to Node.js and would like to read the content of a simple html file, which is either "1" or "0". After that I would like to put it into the variable "sensorReading".

I found out that I could read the content with:

fs =require('fs')
fs.readFile('/home/pi/status.html', 'utf8', function (err,data){
if (err) {
return console.log(err);
}
console.log(data);
});

This gives me either "1" or "0" as a console output. But I would like to have the value in another variable. Here's a snippet of the code which I need it for:

garage
.getService(Service.GarageDoorOpener)
.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED)
.setCharacteristic(Characteristic.ObstructionDetected, Characteristic.ObstructionDetected.NO)
.getCharacteristic(Characteristic.CurrentDoorState)
.on('get', function(callback) {

var err = null;

wpi.setup('phys');
sensorReading = wpi.digitalRead(12);
sensorReading = Number(sensorReading);
if (sensorReading == '1'){
GARAGE_DOOR.opened = false;
}
if (sensorReading == '0'){
GARAGE_DOOR.opened = true;
}

if (GARAGE_DOOR.opened) {
console.log("Query: Is Garage Open? Yes.");
callback(err, Characteristic.CurrentDoorState.OPEN);
}
else {
console.log("Query: Is Garage Open? No.");
callback(err, Characteristic.CurrentDoorState.CLOSED);
}
});

Normally the value for "sensorReading" comes from a GPIO of the Raspberry Pi but I would like to have the value out of my file.

Please forgive me if I named something wrong, or if it's a stupid question but I couldn't find a solution for my kind of task.

Thanks in advance :)

7
  • 1
    just use require() to get the file and blah blah to get the part you want and use var e = eval(partyouwantasvar); and whala! (Note: eval best be used safe as if it's used incorrectly, it can break things) Commented Dec 21, 2017 at 23:00
  • Thanks for the fast answer but I'm sorry, I don't know how I need to put this into my code :/ Commented Dec 21, 2017 at 23:09
  • var myNum = Number(require('filename.txt')); Commented Dec 21, 2017 at 23:11
  • @TyQ. - What are you expecting require() to do with a text file? Commented Dec 22, 2017 at 0:01
  • Get the content Commented Dec 22, 2017 at 0:01

1 Answer 1

1

have you try sensorReading = fs.readFileSync('/home/pi/status.html', 'utf-8')

Sign up to request clarification or add additional context in comments.

1 Comment

This looks like it would work best for me :) Do I have to put fs = require('fs') at the beginning of my script for it to work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.