从内联函数内更新变量

时间:2017-10-08 15:32:44

标签: javascript node.js callback

我在这里度过了难关。我是Node.js的新手,我正在尝试创建一个小的RESTful API来读取存储在目录中文件中的RFID标签数据列表。

我有路由设置,我可以成功读取一个文件的内容。但现在,我想显示目录中可用文件的列表,并创建指向相应API调用的链接以读取raid标记数据。

我的问题是,应该包含相当简单的html的responseContent对象不会使用reader回调函数中的文件列表进行更新。虽然我可以在控制台中看到,目录已正确读入并列出了所有文件。

您可以在下面找到我的代码:

// 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);
})

如上所述,我对node.js相当新,所以我认为这与回调左右有关,但我根本找不到答案。

任何帮助或指向更多帮助的方向,将不胜感激。

Christian

1 个答案:

答案 0 :(得分:0)

res.send()移到try catch中,如下所示。 le应更改为li

// 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 += "<li>" + items[i] + "</li>";
                if (DEBUG) console.log(file);
            }

            responseContent += "</ul></html>";
            res.send(responseContent);

        });
    } catch (err) {
        var msg = "could not read directory " + rfidTagDir + " to list available tags \nException output: " + err.toString();
        console.error(msg);
        res.send(msg);
    }

});