具有响应和http方法的节点JS变量范围

时间:2014-08-26 17:34:50

标签: javascript node.js

我仍然试图掌握这一点,但这对我来说很困惑。所以我使用http.get和管道与bl模块,我希望它改变内容,所以我可以在功能之外使用它不工作为什么?我认为使用var它会在我的文件中全局,这将允许我更改它。

   var http = require('http');
   var bl = require('bl');

   var url1 = process.argv[2];

   var content;

   http.get(url1, function(response){
      response.pipe(bl(function(err,data){
      return data.toString();

     }));
   });
   console.log(content.length);
   console.log(content);

2 个答案:

答案 0 :(得分:1)

您是否尝试修改content?你从不为它分配任何东西然后你试图同步访问它(这几乎肯定会在get完成之前发生)。我假设你想做更多的事情:

   ...
   var content;
   http.get(url1, function(response){
      response.pipe(bl(function(err,data){
         content = data.toString();
         console.log(content.length);
         console.log(content);
     }));
   });

答案 1 :(得分:1)

Node.js是异步的,这意味着您的get函数下面的代码可能会在回调函数内部的代码(作为第二个参数传递的函数)之前执行。

   var http = require('http');

   var bl = require('bl');

   var url1 = process.argv[2];

   var content;

   http.get(url1, function(response){
      response.pipe(bl(function(err,data){
          // After all callbacks have come back, modify content
          content = data.toString(); // Set the value of content
          console.log(content.length);
          console.log(content);
          return content; 
     }));
   });

   // The callback function in get still hasn't been called!
   console.log(content); // undefined
相关问题