gpt4 book ai didi

node.js - Node js 方法结果不一致

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:59 25 4
gpt4 key购买 nike

过去几天我一直在尝试解决以下问题,但似乎无法找到答案。我是 Node 和 JS 的新手(唯一的经验是在线教程)。

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

我一直在阅读有关 Node 中的事件的信息,因此我在代码中使用了一些它们。一个监听器事件提示我输入 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(); 即可检索结果;

关于node.js - Node js 方法结果不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32151848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com