I'm currently working on a project related to home automation using IoT technology. In this project, my websocket server acts as a subscriber to a MQTT broker, receiving temperature and light intensity data from a microcontroller in the form of JSON data. My goal is to save all received data logs into a file; however, when I attempted to do so using .writeFileSync()
, it only displayed [object Object]
. To remedy this, I had to manually edit the data.JSON file before running my program to avoid encountering errors.
Below is the script structure:
var config = require('./data.json');
function writeData() {
fs.writeFileSync('data.json', config);
}
The next approach I tried was:
var config = require('./data.json');
let data2 = JSON.stringify(config);
function writeData() {
fs.writeFileSync('data-2.json', data2);
}
However, I encountered difficulties in locating the file named data-2.json
.
Any assistance with this issue would be greatly appreciated.
EDIT
I have invoked the writeData() function within this section of the code:
s.on('dev:on', function (id) {
if (id == 'lamp1') {
config.lamp1 = true;
} else if (id == 'fan1") {
config.fan1 = true;
}
client.publish(id, "true");
writeData();
console.log('Device ON RECEIVED for ' + id);
});
The remaining sections of the code resemble this snippet.