node.js - Node js中的Request函数后无法读取数据
问题描述
我在 Node js 中有一个使用 cherio 和 requests 的简单代码。问题很有趣,我没有任何错误,但问题是我迭代链接,当我写返回函数时,我将链接附加到堆栈或数组中,我没有取回我的数据
我还添加了评论,因此您可以在我打印时返回数据时阅读我越来越不确定有人可以帮忙吗
/*
Author: Soumil Shah
Website: http://soumilshah.herokuapp.com
*/
try{
const cherio = require('cherio');
const request = require('request');
const fs = require('fs')
console.log('All Modules Loaded ..... ')
}catch(e){
console.log(`Some Packages are missing ${e}`);
}
class Stack{
constructor(){
this.data = []
}
Add(elem){
this.data.push(elem);
}
Size(){
if (this.data.length == 0){return 0;}else{
return this.data.length;
}
}
Pop(){
if (this.data.length == 0){
return -1;
}else{
return this.data.pop()
}
}
isEmpty(){
if(this.data.length == 0){
return true;}
else{
return false;}
}
getStack(){
return this.data;
}
}
class ImageHunter{
constructor(WebsiteUrl = '',BaseUrl = ''){
this.URL = WebsiteUrl; // Website
this._Counter = 0; // Counter for creating File Name Image1.png etc
this.stack = new Stack(); // Stack Data Structure
this.BaseUrl = BaseUrl; // base URl
this.options = {
'method': 'GET',
'url': `${this.URL}`,
'headers': {
}
};
}
Load()
{
const request = require('request');
const cherio = require('cherio');
request(this.options, (err,resp,html)=>
{
if(!err && resp.statusCode ==200)
{
console.log(`Request was Success ${resp.statusCode}`) // success Response
const $ = cherio.load(html); // create a chery Object
$("img").each((index, image)=>{
this.counter = this.counter + 1; // Count of Images
var FileName = "Image"+ this.counter.toString() + '.jpg' // createws FileName
var img = $(image).attr('src'); // find the src
var baseUrl = this.BaseUrl // get Base URl for Images
var Links = baseUrl + img;
if (Links.toString().search(".jpg") > 0){
this.stack.Add(Links);
}
})
}else{
console.log("Error ")
}
// This Works HERE ---- - - - -- -- - - -
console.log(`Stack Size ${this.stack.Size()}`);
// Return Dont WORK
return this.stack.getStack();
})
}
}
var elem;
var image = new ImageHunter(WebsiteUrl='https://www.bridgeport.edu',BaseUrl='https://www.bridgeport.edu');
var data = image.Load();
console.log(data);
解决方案
推荐阅读
- python - 应用程序 exe 已使用 auto-pay-to-exe 实用程序创建。此应用程序 exe 正在打开,但立即关闭
- javascript - 将基于 React 类的组件转换为功能组件
- google-api - 如何在自定义搜索 API 上搜索事件?
- rabbitmq - MassTransit/RabbitMQ:一项服务或多项服务
- python - 在 Tkinter 中更改框架的位置,涉及类和函数
- python - 在区间中找到素数的最快方法
- python - 使用 beautifulsoup 从脚本标签中抓取数据
- node.js - 在nodejs中循环完成后执行条件语句
- javascript - ReactJS - 更改事件上特定按钮的按钮文本
- javascript - JavaScript逗号分隔在没有jQuery的情况下连接数组中的一组元素