get the all feeds data in single array in node.js - mysql

i have one doubt in the node js
i need to get the data from the rss feed
for that i install the rss-parser module in it
https://www.npmjs.com/package/rss-parser
let Parser = require('rss-parser');
let parser = new Parser();
(async () => {
let feed = await parser.parseURL('https://www.reddit.com/.rss');
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})();
the code was like that
here they are using the async function
to get the data feed for one url
i have lot of urls
i need to loop it and get the feed details in single array
is there any posibility
please tell me is there any thing
i need to get the all feed url details in a single array
I tried as of now this
I tried this code
exports.getRssFeedLinks = () => {
// Setting URL and headers for request
// Return new promise
return new Promise((fulfill, reject) => {
// Do async job
let getSql = 'SELECT * FROM `news_feeds`';
//console.log(updateSql);
connection.query(getSql, (error, results, fileds) => {
if(error) {
reject(error);
}
else {
returnResult = JSON.stringify(results);
fulfill(returnResult);
}
});
})
}
exports.errHandler = function(err) {
console.log(err.message);
}
exports.getRssFeeds = (req, res) => {
let parser = new Parser();
let feedLink;
var dataPromise = this.getRssFeedLinks();
//console.log(dataPromise);
dataPromise.then(JSON.parse, this.errHandler)
.then(function(newFeeds) {
// Do one more async operation here
let feedsList = [];
if(newFeeds && newFeeds.length > 0) {
let feedLinks = [];
newFeeds.forEach(feed => {
feedLinks.push(feed.link);
});
(async () => {
let feeds = await Promise.all(feedLinks.map(parser.parseURL));
//feeds will have array of arrays, each array includes the response feed from each url
feeds = [].concat(...feeds) //if you want to flatten the array
feed.forEach(({item}) => {
console.log(item.title + ':' + item.link)
});
feeds.forEach(feed => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})
})();
}
if(feedsList.length >0) {
res.send({
"success" : true,
"result" : feedsList
});
}
else {
res.send({
"success" : true,
"message" : "No Record ",
"result" : feedsList
});
}
}, this.errHandler);
}
Errors
(node:5700) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property
'options' of undefined
(node:5700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

You can use Promise.all to send multiple request.
(async () => {
let feeds = await Promise.all(['https://www.reddit.com/.rss1', 'https://www.reddit.com/.rss2'].map(parser.parseURL));
//feeds will have array of arrays, each array includes the response feed from each url
feeds = [].concat(...feeds) //if you want to flatten the array
feed.forEach(({item}) => {
console.log(item.title + ':' + item.link)
});
//or use loop through each feed
feeds.forEach(feed => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})
})();

Related

How to extract key and value from json in fetch method in React Native?

I'm new in React Native. I would like to extract a value from json with fetch to do a simple test to begin. But I don't understand, how to select a particular key from Json. Always, I have undefined return. I tried to modify my code with this post but it doesn't work. I tried to parse before but he didn't want because it's already an object.
This is my code:
checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch('https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=' + name + '%20' + surname, {
method: 'GET',
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson.ind == 'Individu non trouv\u00e9 !') {
alert("Id incorrect")
}
else {
alert("Id correct");
}
alert(JSON.stringify(responseJson.ind))
}).catch((error) => {
console.error(error);
});
}
This is my JSON format:
[{"iuf":"1366701","ind":"LEBRUN L\u00e9o (2000) H FRA - CN BEAUPREAU","sex":"#1e90ff","clb":"CN BEAUPREAU"}]
I know my request work because when I run this code alert(JSON.stringify(responseJson)).It return the entire json. So I don't know, how to resolve the undefined return.
Regards
Your json is an array, you either need to loop through it if there is multiple items inside, or just use responseJson[0] to read it. So if you want to read your json, your code would look like this :
const checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname,
{
method: "GET"
}
)
.then(response => response.json())
.then(responseJson => {
// Since you have only one object inside your json, you can read the first item with 'responseJson[0]'.
if (responseJson[0].ind == "Individu non trouv\u00e9 !") {
alert("Id incorrect");
} else {
alert("Id correct");
}
alert(JSON.stringify(responseJson[0].ind));
// If you have multiple elements inside your responseJson,
// then here is a loop example :
// responseJson.forEach(item => {
// console.log('item ind = ', item.ind);
// });
})
.catch(error => {
console.error(error);
});
};
Use async await.
const checkLogin = async () => {
const { name } = this.state;
const { surname } = this.state;
const request = await fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname)
const response = await request.json();
console.log('result from server', response)
}

How do I return files as base-64 data URL strings from my API using MongoDB/GridFS?

I have a collection of Contacts inside my MongoDB
Those Contacts have avatars (or "profile pictures")
Here is the profile picture for the above user:
... and a chunk of that file (there's only one).
I'm trying to take ^^^ that ^^^ chunk and parse it into a base-64 data URL in order to return it from my server back to my application and use it inside an <img>'s src attribute.
app.get('/queryContacts', (req, res) => {
const getContacts = async query => {
let contacts = await db
.collection('contacts')
.find(query)
.toArray();
return contacts;
};
const getImages = async id => {
let imageUrl = 'data:image/jpg;base64';
await bucket
.openDownloadStream(new ObjectID(id))
.on('data', chunk => {
imageUrl += chunk.toString('base64');
})
.on('end', () => {
return imageUrl;
});
}
getContacts({account_id: new ObjectID(req.query.id)}).then(contacts => {
Object.keys(contacts).forEach(key => {
getImages(contacts[key].image_id).then(url => {
console.log(url); // undefined
contacts[key].imageUrl = url;
});
});
res.json(contacts);
});
});
The problem is that when I try this, the URL is undefined because getImages() isn't waiting for the 'end' event to finish.

How to fix Cannot set headers after they are sent to the client?

After reading up on this topic for the last 2.5 hours I cant determine how to fix my: Cannot set headers after they are sent to the client issue, but I think it has to do with the below code at the bottom especially the code is in bold.
Any help or assistance will be greatly appreciated.
app.post("/api/tracking/retrieve", (req, res) => {
res.setHeader('Content-Type', 'application/json');
// before all the iterations
const trackingCodes = ['EZ6000000006', 'EZ4000000004'];
const carrierCodes = ['UPS', 'UPS'];
trackingCodes.forEach((trackingCode) => {
carrierCodes.forEach((carrierCode) => {
const tracker = new api.Tracker({
tracking_code: trackingCode,
carrier: carrierCode
})
tracker.save().then(function (data) {
table = 'tracking_table';
col = ['user_id', 'tracking_number'];
val = [user_id, tracker.tracking_code];
**// !ISSUE: :: ::: :::: ::::: :::::: ::::::: //**
main.create(table, col, val, function (data) {
res.send(JSON.stringify({
id: "",
user_id: user_id,
tracking_number: data.tracking_code
})); // replace this for your res.json()
});
}
)
.catch(error => {
// handle errors
console.log('There has been an error with your submission.')
});
})
})
res.end()
});
As #kiran Mathew has answered, the res.json() are called again and again inside for loop which is why 'cannot set headers after response sent' occurs.
You could have a result array 'trackingNumbers' to store all tracking_number and later exiting from the loop, sent a single response.
app.post("/api/tracking/retrieve", (req, res) => {
const trackingCodes = ["EZ6000000006", "EZ4000000004"];
const carrierCodes = ["UPS", "UPS"];
const trackingNumbers = [];
trackingCodes.forEach(trackingCode => {
carrierCodes.forEach(carrierCode => {
const tracker = new api.Tracker({
tracking_code: trackingCode,
carrier: carrierCode
});
tracker
.save()
.then(function(data) {
table = "tracking_table";
col = ["user_id", "tracking_number"];
val = [user_id, tracker.tracking_code];
// !ISSUE: :: ::: :::: ::::: :::::: ::::::: //**
main.create(table, col, val, function(data) {
// res.json({
// id: "",
// user_id: user_id,
// tracking_number: data.tracking_code
// });
trackingNumbers.push(data.tracking_code);
});
})
.catch(error => {
// handle errors
console.log("There has been an error with your submission.");
});
res.json({
id: "",
user_id: user_id,
tracking_number: trackingNumbers
});
});
});
});
The issue with your code is you are calling res.json() in an iterative loop.
You should call that only once since
res.json() implements res.write(),res.setHeaders() and res.end() under the hood,
which means once res.end() is called it ends the request and cannot send anymore.
You are better off writing the responses using
res.setHeader('Content-Type', 'application/json'); // before all the iterations
res.send(JSON.stringify({key:"value"})); // replace this for your res.json()
res.end() // after iterations

Creating a JSON - Angular 5

I have a JSON read to UI and modifiled as part of review process. Finally I want to save New data to a New folder/File.
Code Sample below - Always ends with POST call in error :
SaveFinalData(){
this.postJson<Reaction>
('./assets/ICP/Reviewed/Json/out.json',
this.reactionDatabase.reactiondataChange.value);
}
postJson<Reaction>(url: string, Reaction: any){
//let body = JSON.stringify({ Reaction });
this.http.post(url, body)
.subscribe(
(val) => {
console.log("POST call successful value returned in body", val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
}
Have tried below 2 alternatives:
(1)
var theJSONdata = JSON.stringify({ Reaction });
window.localStorage.setItem('./assets/ICP/Reviewed/Json/out.json', theJSONdata)
Result -- NO LUCK!
(2)
var jsonfile = require('jsonfile')
var file = './assets/ICP/Reviewed/Json/out.json'
var obj = {name: 'JP'} //SAMPLE DATA
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Result -- NO LUCK! --> GIVES ERROR fs.writeFile is not a function
Pls kindly help/guide me to reach the final result....Thanks

TextDecoder failing in ES6 Promise recursion

I'm attempting to query an API which responds with a ReadableStream of XML.
The code below uses a recursive Promise. Recursive because it sometimes doesn't decode the stream in a singular iteration and this is whats causing my headache.
While I'm successfully fetching the data, for some reason the decoding stage doesn't complete sometimes, which leads me to believe it's when the stream is too large for a single iteration.
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then((response) => {
console.log('fetch complete');
this.untangleCats(response);
})
.catch(error => {
this.state.somethingWrong = true;
console.error(error);
});
}
untangleCats({body}) {
let reader = body.getReader(),
string = "",
read;
reader.read().then(read = (result) => {
if(result.done) {
console.log('untangling complete'); // Sometimes not reaching here
this.herdingCats(string);
return;
}
string += new TextDecoder("utf-8").decode(result.value);
}).then(reader.read().then(read));
}
I think that the next iteration was sometimes being called before the current iteration had completed, leading to incorrectly concatenation of the decoded XML.
I converted the function from sync to async and as a regular recursive method of the component rather than a recursive promise with a method.
constructor({mode}) {
super();
this.state = {
mode,
string: "",
cats: [],
somethingWrong: false
};
}
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then( response => this.untangleCats( response.body.getReader() ) )
.catch(error => {
this.setState({somethingWrong: true});
console.error(error);
});
}
async untangleCats(reader) {
const {value, done} = await reader.read();
if (done) {
this.herdingCats();
return;
}
this.setState({
string: this.state.string += new TextDecoder("utf-8").decode(value)
});
return this.untangleCats(reader);
}