简体   繁体   English

nodejs变量未传递给内部函数

[英]nodejs variable not passing to an inner function

So I have written the code below but am not able to get the inner function .each to be able to call res.write with the results from the MongoDB query. 所以我写了下面的代码,但无法获取内部函数.each ,以便能够使用MongoDB查询的结果调用res.write

I initially believed that the problem could be due to the fact that the variable res was not global, but even after trying it as a global variable it still did not work, and it being global or not should not affect the code because the .each function is inside of the showSidebarData function that is being passed the res string. 我最初认为问题可能是由于变量res不是全局变量,但即使尝试将其用作全局变量,它仍然不起作用,无论是否为全局变量都不会影响代码,因为.each函数位于正在传递res字符串的showSidebarData函数内部。

function showSidebarData(res){
  res.writeHead(200, {'Content-Type': 'text/html'});
  coll.find({}, function(err, cursor) {
    item = new Array();
    cursor.each(function(err, doc) {
      if(doc!==null){
        item.push(doc);
      }else{
        var data = {
          "item": item
        };
        fs.readFile('/usr/share/node/pathtofile.html', 'utf8', function(err, html){
          if (err) {
            console.log(err);
          }
          res.write(dispatcher.templateEngine(html, data));
        });
      }
    });
  });
}

My goal is to be able to write the results from the template engine function inside the file read to the data stream inside of res . 我的目标是能够将读取的文件中的模板引擎函数的结果写入res的数据流中。 As a side note, the else statement for if(doc!==null) is always run after all the collection query results have been iterated over. 附带说明一下, if(doc!==null)的else语句始终在迭代所有集合查询结果之后运行。

the function that was calling showSidebar() was using the correct scope but because of the nature or javascript the respose was being closed before the file stream was done reading the file and wanted to write to res . 调用showSidebar()的函数使用的是正确的作用域,但是由于性质或javascript的原因,在文件流完成读取文件并想写入res之前,已关闭showSidebar() the solution was to comment out res.end() in the code below. 解决方案是在下面的代码中注释掉res.end()

dispatcher.onGet("/admin/leftSidebar", function(req, res) {
        if(req.params.cookies.session=="session-key"){
showSidebarData(res);

}else{
 res.write("sorry but your username and/or password was invalid please go try brute forcing someone elses site");   
}
// commenting out the line below makes this code work 
    res.end();
});

I would like to thank @johnnyHK for the help. 我要感谢@johnnyHK的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM