I'm having a hard time here. I'm fairly new to Node.js and am trying to create a little RESTful API to read a list of RFID Tag data stored in files in a directory.
I have the routes setup and I can successfully read the content of one file. But now, I'd like to show a listing of available files from a directory and create links to the corresponding API calls to read the raid tag data.
My problem is, the responseContent object that shall contain the rather simple html, is not updated with the list of files from within the function in the reader callback. Although I can see in the console, that the directory is correctly read in and all files are listed.
Below you can find my code:
// get the listing of all stored rfid tags
app.get("/rfid/tags", function(req, res) {
if (DEBUG) console.log("list all rfid tags requested");
// create a shiny html response content to show in the browser:
var responseContent = "<html><h1>List of all RFID Tags</h1>RFID Tag Files:<ul>"
try {
fs.readdir(rfidTagDir, function(err, items) {
if (DEBUG) console.log(items);
for (i in items) {
var file = items[i].toString().substring(0,items[i].indexOf('.'));
responseContent += "<le>"+items[i]+"</le>";
if (DEBUG) console.log(file);
}
});
} catch (err) {
console.error("could not read directory "+rfidTagDir+" to list available tags \nException output: " + err.toString());
}
responseContent += "</ul></html>";
res.send(responseContent);
})
As said, I'm fairly new to node.js so I reckon this has something to do with it being a callback or so, but I simply can't find an answer to this.
Any help or pointing in the direction of more help, would be greatly appreciated.
Christian