节点js中的方法结果不一致

时间:2015-08-22 03:04:37

标签: node.js web-scraping eventemitter

在过去的几天里,我一直试图想出以下几点,似乎无法找到答案。我是node和JS的新手(只有经验是在线教程)。

我正在尝试创建一个类(函数)来从网站中删除源代码。我想从命令行读取一个url并返回html内容。但是,当我以不同的方式运行代码时,我似乎得到了不同的结果(我认为我应该得到相同的结果)。

我一直在阅读节点中的事件,所以我在代码中使用了一些。一个侦听器事件提示我输入url然后在设置url之后它(侦听器函数)发出一条消息,该消息由另一个侦听器拾取并且取出html内容。

我遇到的问题是,当我创建对象的实例时,似乎代码的请求部分不会执行。但是,如果我从实例中调用该方法,则会从页面的html内容中打印出来。

感谢任何帮助。感谢。

function test() {
  var events = require('events').EventEmitter;
  var request = require('request');
  var util = require('util');

  var that = this;
  that.eventEmitter = new events();
  that.url = 'http://www.imdb.com/';

  that.eventEmitter.on('setURL',that.setUrl = function(){
    console.log("Input the URL: ");
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    process.stdin.on('data', function (text) {
      that.url = util.inspect(text);
      that.url = that.url.substr(1, that.url.length - 4);
      that.eventEmitter.emit('Get url html');
      process.exit();
    });
  });

  that.eventEmitter.on('Get url html',that.httpGet = function() {
    console.log("Fetching... " + that.url);

    request(that.url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the Google homepage.
      } else {
        console.log("Error Encountered");
      }
    });
  });

  that.eventEmitter.emit('setURL');
}

var scrapper = new test(); //This asks me for the url and then only executes to first line of that.httpGet.

scrapper.httpGet(); // This gives the desired results from that.httpGet

1 个答案:

答案 0 :(得分:0)

我使用提示库https://www.npmjs.com/package/prompt

解决了问题
function test() {
  var events = require('events').EventEmitter;
  var prompt = require('prompt');
  var request = require('request');
  var util = require('util');

  var that = this;
  that.eventEmitter = new events();
  that.url = 'http://www.imdb.com/';

  that.eventEmitter.on('setURL',that.setUrl = function(){
    prompt.start();
    process.stdin.setEncoding('utf8');

    prompt.get(['url'], function( err, result ) {
      that.url = result.url;
      that.eventEmitter.emit('Get url html');
    } );
  });

  that.eventEmitter.on('Get url html',that.httpGet = function() {
    console.log("Fetching... " + that.url);

    request(that.url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body); // Show the HTML for the Google homepage.
      } else {
        console.log("Error Encountered");
      }
    });
  });

  that.eventEmitter.emit('setURL');
}

var scrapper = new test(); //This asks me for the url and then only executes to first line of that.httpGet.

// scrapper.httpGet(); // This gives the desired results from that.httpGet

我从命令行运行脚本,输入http://www.google.com并检索结果,而无需额外调用scrapper.httpGet();