Store imap.fetch result in a variable and iterate anytime - node.js

I am trying to store the result from imap.fetch() into a variable, so that i can iterate it whenever i want to check all mail.
But it is not working when i call my getAllMail() from another class, Thanks for any help.
let allSearch;
imap.search(['All', ['ON', date]], (err,res) => {
if (err) console.log(err)
else {
allSearch = imap.fetch(res, {bodies:'HEADER.FIELDS (FROM SUBJECT)', struct:true})
}
})
function getAllMail() {
allSerch.on('message', (msg, seq) => {
console.log()
})
}
module.exports.getAllMail = getAllMail

Related

How to return an object within inside for loop

I want to return "items" which is inside the for loop and also two additional functions."Items" is an object (I would not say variable) which consists of three array elements and that can be more depending on the situation. So I need to return "items" so I can access it outside and I can send it to the client using res.send(). If I send data inside the loop and function, it is returning with an error called "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client". I found the fix for it but on implementing them, nothing is happening. It is throwing me the same error. I was thinking to do it call back function but I am confused about how to use it in this case. Thanks in advance.
router.get("/send" , async (req, res) => {
try {
res.send("hello")
//await sendData()
getCollectionNames()
} catch (error) {
console.log(error);
}
function getCollectionNames(){
MongoClient.connect(url, function(err, db) {
var db = db.db('admin')
mongoose.connection.db.listCollections().toArray(function (err, names) {
for(let index = 0; index < names.length; index ++){
if (err) {
console.log(err);
}
let name = names[index].name
const collection = db.collection(name)
collection.find().toArray(function(err, items){
console.log(items)
})
}
});
})
}
})

Code after the for loop is getting executed before the loop runs in node.js

In the code below, I'm fetching data from an API end point by using Promise.all(). The results are mapped to the urls and I have to iterate over them in order to process the results. But the code after the loop keeps getting execute before the loop. How do I fix this?
Thank you.
Code:
con.collection("users").find(input).toArray((error,results) => {
if(error){
throw error;
}
if(!results.length){
response.json({"msg":"user not found"});
} else{
//call google maps API to get address an make inverse index entry
//call gmaps API for each location
//form urls
urls = []
locations.forEach(location => {
lat = location.lat;
long = location.long;
urls.push( url+lat.toString()+","+long.toString()+"&key="+API_KEY)
});
console.log(urls);
var locations_temp = []
Promise.all(urls.map(url_ =>
fetch(url_)
.then(checkStatus)
.then(parseJSON)
.catch(error => console.log("There was an error",error))
))
.then(data => {
data.forEach((entry,index) => {
console.log(entry.results[0].formatted_address);
locations_temp.push(entry.results[0].formatted_address);
})
});
//this gets executed before the loop above.
console.log(locations_temp);
console.log("here");
console.log("locations:",locations_temp);
//USER EXISTS, APPEND LOCATIONS
filter = {$push:{locations:{$each:locations_temp}}};
con.collection("users").update(input,filter)
.then(() => response.sendStatus(200))
.catch((error) => {throw error});
}
});
};

Parsing line by line in discord bot (node.js)

I'm making a discord bot with node.js and I have a .txt file with 3 lines:
User1|421
User2|5543
User3|12
And I want to parse only numbers after '|', I've used
fs.readFile('balance.txt', 'utf8', function(err, contents) {
message.channel.sendMessage(contents);
})
to get the text from it, what I want to do is check if the user that sends the request to check balance exists in the list, and if it exists print out the balance.
I'd like for the input to be
!balance
and output to be
$43
while checking:
User exists?
Get line in which the user is in
Get number after '|' and store it in a temporary variable to print
Thanks!
I'd try this approach, read this file into memory and create an accessor function for it:
const fs = require("fs");
const os = require('os');
fs.readFile('balance.txt', 'utf8', function(err, contents) {
if (err) {
console.error("Error occurred: ", err);
} else {
let balancesDetails = getUserBalances(contents);
let user3BalanceDetails = balancesDetails.find(result => result.user === "User3");
console.log("User 3 balance: ", user3BalanceDetails.balance);
// Send the balance if required
//message.channel.sendMessage(user3BalanceDetails.balance);
}
});
function getUserBalances(fileContents) {
return fileContents.split(os.EOL).map(line => line.split("|")).map(([user, balance]) => { return { user, balance: parseFloat(balance)} });
}
An example of this working in plain JavaScript would be like below (the only real difference is we can't use the OS object since this is Node.js only!):
let contents = `User1|421\nUser2|5543\nUser3|12`;
function getUserBalanceArray(fileContents) {
return fileContents.split('\n').map(line => line.split("|")).map(([user, balance]) => { return { user, balance: parseFloat(balance)} });
}
function getUserBalanceMap(fileContents) {
return fileContents.split('\n').map(line => line.split("|")).reduce((map, [user, balance]) => { map[user] = parseFloat(balance);
return map }, {});
}
console.log("File contents:\n" + contents);
console.log("Balance array: ", getUserBalanceArray(contents));
console.log("Balance map: ", getUserBalanceMap(contents));

Loopback: how to collect data in a for-loop containing a async method?

Using loopback I have a simple for loop in which I perform a findOne:
let my_data = [];
Orders.forEach(function(order,idx) {
let postalcode = order.toJSON().customer.postal_code;
let ps4 = postalcode.slice(0,4);
app.models.postalcode.findOne({where: {postal_code: parseInt(ps4)},include: ['depot']}, function (err, Postalcode) {
if (err) {
winston.error('Could not load postalcode %s due to error %s: ', ps4, err.message);
} else {
if (Postalcode) {
let depot = Postalcode.toJSON().depot;
if (!depot) {
//
} else {
let depot_city = depot.city;
if (cities_to_process.indexOf(depot_city) > -1) {
my_data.push(order);
} else {
}
}
} else {
winston.warn('Could not find postal code %s', ps4)
}
}
});
});
console.log(my_data);
After the for loop I would like to do something with the collected data in my_data. Since findOne appears to be asynchronous, what is the preferred way of doing this?
Use async library. It will be easy for you to use async.eachSearies() to loop the async functions in series and get the desired output. You can take a reference here link
You can create new promises in forEach like:
let Y = X.forEach((item) => {
return new Promise((resolve, reject) => {
resolve('done')
})
})
Promise.all(y, callback)

Access variable inside function and block

I am playing around with some nodeJs things, I read about block and functions scooping but I was not able to access my variable jsonArrayObj:
csv({delimiter: [' ']})
.fromFile(csvFilePath)
.on('end_parsed', function(jsonArrayObj) {
console.log(jsonArrayObj);
function cssResult() {
return jsonArrayObj;
}
})
.on('error', (err) => {
console.log(err);
});
console.log('jsonArrayObj'); // I want to print the results here also
You can do it something like this.
csv({delimiter: [' ']})
.fromFile(csvFilePath)
.on('end_parsed', function(jsonArrayObj) {
console.log(jsonArrayObj);
myNewFunc(jsonArrayObj);
function cssResult() {
return jsonArrayObj;
}
})
.on('error', (err)=>{
console.log(err);
});
var myNewFunc = function(myVar){
console.log(myVar); // this will be your result
};
Your variable jsonArrayObj is just defined on your function's scope. So jsonArrayObj is just accessible in your function.
If you want to use it out of your function, you have to define a variable outside of your function, and then tell your function that this variable takes jsonArrayObj's value.
Like this :
var myRes;
csv({delimiter: [' ']})
.fromFile(csvFilePath)
.on('end_parsed', function(jsonArrayObj) {
myRes = jsonArrayObj;
console.log(jsonArrayObj);
function cssResult() {
return jsonArrayObj;
}
})
.on('error', (err)=>{
console.log(err);
});
console.log(myRes);

Resources