Nodered/uibuilder reading json files

uibuilder works well to migrate my older project to NR/uib.
Problem (atm) is to get/read json file(s) to use that data in index.js.
(And yes, I need to read dircetly from rpi files!)

Followed @knolleary advice with /handling-json-in-the-file/7823.. added
to ~/.node-red/settings.json

functionGlobalContext: {

On the RPI installed 'fs' with ~/.node-red $ npm install fs

In index.js :

var fs = global.get('fs');             <--- this is line #35
const jsonString = fs.readFileSync("./plus/stringsPlus.json");
const stringsPlus = JSON.parse(jsonString);

Restarting NR and reloading the NR/uibuilder page, the DeveloperConsole gives:

    Uncaught ReferenceError: global is not defined
        at index.js:35:10

Is this methode not valid for NR/uibuilder?
Maybe I have a config error, but how to debug this?

The index.js runs in your users browser, global and fs run in node-red on the server. So no, you can't use global or the fs library in index.js. The global is node-red only - it only works in flows. fs is node.js and only works in the node.js context (in function nodes from a node-red perspective).

The real question is: Do you want to read the JSON file and process it in Node-RED and then send some data to your front-end (the browser) or do you want to read the JSON file into the browser?

Reading the file in Node-RED is easier (less manual code to write). Node-RED has the file read and json nodes which between them get the file (from the server's filing system) and converts the JSON to a JavaScript object. You can then send that to your front-end by outputting direct to the uibuilder node. It arrives in the browser as a fully functional JavaScript object.

afaiu with index.js and index.html etc I'm reading it into the 'browser'.

OK, but did you see my last bit:

You can read the file in Node-RED and send the data to the browser. Or you can indeed read the file straight into the front end - but only by making it available as a static file that the browser has to effectively download from the web server (using something like the fetch function in JavaScript.

Maybe this diagram will help you understand the different contexts that Node-RED and the browser are running in?

To read the JSON direct into the index.js - you must first put it in the server filing system. Then make it available to the web server (most commonly by putting it into the same folder as the index.js file). Then you must fetch it from the web server.

To send the JSON data to index.js - you first read it into Node-RED from the server filing system as a plain file. Then run it through the JSON node to turn the text into data. Then send it into the uibuilder node. Finally, you can handle it in the front-end via a `uibuilder.onChange('msg', (msg) => { ... }) function.

1 Like

Seems I should rethink the approach ... good starting point for tomorrow :wink:
Thanks for the moment.

1 Like