node-red-contrib-keyvalue-r2
Version:
Node-RED nodes for reading and writing key-value pairs in a JSON file.
30 lines (25 loc) • 763 B
JavaScript
const fs = require('fs');
const path = require('path');
module.exports = function (RED) {
function KeyValueWrite(config) {
RED.nodes.createNode(this, config);
const node = this;
const filePath = config.filePath;
node.on('input', function (msg) {
try {
const key = msg.topic;
const value = msg.payload;
let data = {};
if (fs.existsSync(filePath)) {
data = JSON.parse(fs.readFileSync(filePath));
}
data[key] = value;
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
node.send(msg);
} catch (error) {
node.error('Error writing JSON file: ' + error.message);
}
});
}
RED.nodes.registerType('keyvalue-write', KeyValueWrite);
};