节点JS需要获取htmlcode

时间:2017-01-10 15:29:09

标签: javascript node.js

我想在var中保存extern站点的HTML。我有以下代码:
program.js

var request = require('request');

var htmlcode = "Code isn't defined right now!";

var siteUrl = "http://fluxnetz.de"
request({

uri: siteUrl,
}, function(error, response, body){
var htmlcode = body;
console.log(htmlcode);
}
);
//console.log(htmlcode);

当我想在请求函数之外输出 htmlcode 时,它输出"现在没有定义代码!" 但是我之前将 htmlcode 设置为body。当我调用console.log 里面的函数时,我得到了正确的输出,但是如果我在外面再次运行它就不会工作。

2 个答案:

答案 0 :(得分:0)

您需要了解Javascript的工作原理。 有同步动作和异步动作。

同步表示代码按行

的顺序执行

异步意味着代码不按行顺序执行,而是以线程方式执行。

当您创建新的“请求”时,映像节点打开一个新线程,仅与该reaquest的主体相关。当请求自行解析时,线程会加入到全局程序中。

例如,如果你做的是,而不是同步的console.log(htmlcode);,一个比请求晚解决的异步动作,它将起作用,因为请求的线程已经加入。

最天真,通常不起作用的例子是:

setTimeout(() => console.log(htmlcode), 10000)

等待10秒,然后打印。有足够的时间来完成请求。

正确的方法,就是创建一个函数,叫做“afterRequest” 并从请求中调用该函数解决回调

答案 1 :(得分:-1)

原因是你在回调中确定了另一个局部变量

  var request = require('request');
  var htmlcode = "Code isn't defined right now!";

  var siteUrl = "http://fluxnetz.de"
  request({ uri: siteUrl, 
             function(error, response, body){
                 //var htmlcode = body; // Remove to var and you will address to global variable you wanted.
                 htmlcode = body;  
                 console.log(htmlcode);
              }
          });