不一致的方法导致节点js

Inconsistent method result in node js

过去几天我一直在尝试找出以下问题,但似乎无法找出答案。我是node和JS新手(唯一的经验就是网上教程)

我正在尝试创建一个 class(函数)来从网站上抓取源代码。我想从命令行读取 url 和 return 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

我使用提示库解决了问题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();