简体   繁体   中英

Node.js - How to read data from a file and integrate the output into variable

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 :)

您是否尝试sensorReading = fs.readFileSync('/home/pi/status.html', 'utf-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM