I am trying to exit the script if there are no emails that match our search criteria. If I don't do imap.end(), it never terminates. When I add the imap.end, I get an ECONNRESET. What's the proper way to exit out of IMAP early?
function openInbox(cb) {
imap.openBox('[Gmail]/All Mail', true, cb);
}
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
const aDayAgo = moment().subtract(1,'d');
imap.search([ ['SUBJECT', DPR_SUBJECT], ['SINCE', aDayAgo] ], function(err, results) {
if (err) throw err;
if (results.length == 0){
logging.log("No mail");
db.disconnect();
imap.end();
return;
}
var f = imap.fetch(results, {
bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
struct: true
});
f.on('message', function(msg, seqno) {
logging.verbose('Message #%d', seqno);
msg.once('end', function() {
logging.verbose(prefix + 'Finished');
});
});
f.once('error', function(err) {
logging.verbose('Fetch error: ' + err);
});
f.once('end', function() {
logging.log('Done fetching all messages!');
db.disconnect();
imap.end();
});
});
});
});
imap.once('error', function(err) {
logging.error(err.stack);
});
imap.once('end', function() {
logging.verbose('Connection ended');
});
exports.checkForMail = () => {
return imap.connect();
}
Related
I am using async parallel to get data from db in parallel.
When every task is returning the data I am storing it in local object.
From index.js I am calling cacheService.js .
In cacheService.js I am loading data from mysql database and mongo database in to cache object.
Whenever I am doing npm run local run. I am getting following error.
UNHANDLEDREJECTION Error: Callback was already called.
This error is coming from loadMongoData method of cacheService.js.
I have followed other answers on stackoverflow like adding else part
Here is code for cacheService.js.
'use strict';
var cache = [];
class cacheService {
async init() {
await this.loadMongoData();
}
loadMongoData(env, callback1) {
const _this = this;
console.log('Inside loadMongoData')
async.parallel(
{
task1: function (callback) {
CriteriaDef.find({})
.lean()
.exec(function (err, criteriaDefs) {
if (err) {
console.log('Inside err 1')
logger.error('Error fetching CriteriaDef: ', util.inspect(err));
callback(err, null);
} else if (criteriaDefs) {
console.log('Inside criteriaDefs')
if (criteriaDefs.length && criteriaDefs.length > 0) {
console.log('Inside criteriaDefs 1')
global.CRITERIA_DEFS = criteriaDefs;
cache['criteria_defs'] = criteriaDefs;
}
callback(null, null);
}
});
},
task2: function (callback) {
groupDef
.find({})
.lean()
.exec(function (err, groupDefs) {
if (err) {
console.log('Inside err2')
logger.error('Error fetching groupDefs: ', util.inspect(err));
callback(null, err);
} else if (groupDefs) {
console.log('Inside ')
global.groupDefsWithRoles = groupDefs;
let _groupDefs = [];
_.each(groupDefs, function (groupDef) {
var data = {
value: groupDef._id,
label: `${groupDef._id}: ${groupDef.description}`
};
_groupDefs.push(data);
});
global.groupDefs = _groupDefs;
cache['groupDefs'] = _groupDefs;
logger.info('Loaded groupDefs: ', global.groupDefs.length);
callback(null, null);
}
});
},
task3: function (callback) {
jiraProjects.find({$or: [{archived: {$ne: true}}, {archived: {$exists: false}}]}).exec(function (err, jiraProjects) {
if (err) {
console.log('Inside error 3')
logger.error('Error fetching jiraProjects: ', err);
callback(null, err);
} else if (jiraProjects) {
console.log('Inside jira project')
let _jiraProjects = [];
_.each(jiraProjects, function (jiraProject) {
var data = {
value: jiraProject.key,
label: jiraProject.key,
issueType: jiraProject.issueType ? jiraProject.issueType : 'Bug'
};
_jiraProjects.push(data);
});
global.jiraProjectsList = _jiraProjects;
cache['jiraProjects'] = _jiraProjects;
logger.info('Loaded jira projects: ', global.jiraProjectsList.length);
callback(null, null);
}
});
},
task4: function (callback) {
console.log('Inside task4')
callback(null, null);
},
task5: function (callback) {
inputElements
.find({})
.lean()
.exec(function (err, inputElements) {
if (err) {
console.log('Inside error5')
logger.error('Error fetching inputElements: ', util.inspect(err));
callback(null, err);
} else if (inputElements) {
console.log('Inside inputelements')
global.INPUT_ELEMENTS_DEF = inputElements;
cache['INPUT_ELEMENTS_DEF'] = inputElements;
callback(null, null);
}
});
},
task6: function (callback) {
console.log('Inside task6')
sisp.loadProducts('', callback);
}
},
function (err, results) {
if (err) {
console.log('Inside final error')
logger.error("Something went wrong can't start the app: ", util.inspect(err));
callback1(null, err);
} else {
console.log('Inside final else')
logger.info('loaded all globals properly :)');
callback1(null, null);
}
}
)
}
}
export default new cacheService();
I think your problem cuz you use callback inside of promise.
Please change your code like this:
class cacheService {
async init() {
await new Promise((resolve, reject) => {
this.loadMongoData(env, (ignoreArg, error) => {
if (error) {
return reject(error);
}
resolve();
});
});
}
...
}
Tip: in the each task add statement else for call callback, because maybe your statement not handled and your code can't execute prefect
task1: function (callback) {
CriteriaDef.find({})
.lean()
.exec(function (err, criteriaDefs) {
if (err) {
console.log('Inside err 1')
logger.error('Error fetching CriteriaDef: ', util.inspect(err));
callback(err, null);
} else if (criteriaDefs) {
console.log('Inside criteriaDefs')
if (criteriaDefs.length && criteriaDefs.length > 0) {
console.log('Inside criteriaDefs 1')
global.CRITERIA_DEFS = criteriaDefs;
cache['criteria_defs'] = criteriaDefs;
}
callback(null, null);
} else {
callback(null, null);
}
});
},
I'm trying to implement node-imap and I need to get all the emails received from and sent to an email id.
I've been able to use https://developers.google.com/oauthplayground to generate a refresh token but it expires in an hour so I need a method to generate it directly from the code and In the search request response I'm not getting any message subject or anything.
let Imap = require("imap"),
inspect = require("util").inspect,
config = require('lt-config'),
xoauth2 = require("xoauth2"),
xoauth2gen,imap;
xoauth2gen = xoauth2.createXOAuth2Generator({
user: "mymailid",
clientId: config.MAIL_GOOGLE_CLIENT_ID,
clientSecret: config.MAIL_GOOGLE_CLIENT_SECRET,
refreshToken: config.MAIL_REFRESH_TOKEN,
accessToken: config.MAIL_ACCESS_TOKEN
});
function getAuthorizedImap() {
return new Promise((resolve, reject) => {
xoauth2gen.getToken(function(err, token) {
if (err) {
return console.log(err);
}
console.log("AUTH XOAUTH2 " + token);
config.xoauth2 = token;
imap = new Imap({
user: "test#example.com",
xoauth2: token,
host: "imap.gmail.com",
port: 993,
tls: true
});
imap.once("ready", function() {
resolve(imap);
});
imap.once("error", function(err) {
console.log(err);
});
imap.once("end", function() {
console.log("Connection ended");
});
imap.connect();
});
setTimeout(() => reject('Timeout get token process'), 6000);
})
}
function filterMails(emailId) {
return new Promise(async resolve => {
try {
imap = await getAuthorizedImap();
openInbox(function(err, box) {
if (err) throw err;
imap.search([ ['HEADER', 'FROM', emailId] ], function(err, results) {
if (err) throw err;
console.log("results", results);
var f = imap.fetch(results, { bodies: "HEADER.FIELDS (FROM TO SUBJECT DATE)" });
f.on("message", function(msg, seqno) {
console.log("Message #%d", seqno);
var prefix = "(#" + seqno + ") ";
msg.on("body", function(stream, info) {
console.log(prefix + "Body");
console.log("Body received", info);
});
msg.once("attributes", function(attrs) {
console.log(
prefix + "Attributes: %s",
inspect(attrs, false, 8)
);
});
msg.once("end", function() {
console.log(prefix + "Finished");
});
});
f.once("error", function(err) {
console.log("Fetch error: " + err);
});
f.once("end", function() {
console.log("Done fetching all messages!");
imap.end();
});
});
});
} catch(e) {
console.log("Errror while getting emails from GMAIL ====>>", e);
}
});
}
function openInbox(cb) {
imap.openBox("INBOX", true, cb);
}
module.exports = filterMails;
I want a JSON response from search and to generate a refresh token dynamically. Any help will be appericiated.
Can someone explain me below code snippet? Here how and when .on method with tags "error" and "close" executes when it is not emitted anywhere.
function start() {
amqp.connect(process.env.CLOUDAMQP_URL + "?heartbeat=60", function(err, conn) {
if (err) {
console.error("[AMQP]", err.message);
return setTimeout(start, 1000);
}
conn.on("error", function(err) {
if (err.message !== "Connection closing") {
console.error("[AMQP] conn error", err.message);
}
});
conn.on("close", function() {
console.error("[AMQP] reconnecting");
return setTimeout(start, 1000);
});
console.log("[AMQP] connected");
amqpConn = conn;
whenConnected();
});
}
I have this code with callbacks:
function getUserToken(data, callback) {
var password_sha256 = sha256(data.password);
getAppById(data.app_id).then(function(res) {
console.log("app"+res);
if (!res) {
console.log("No app");
callback(err, { meta: {
code: 403,
error_message: "There are no app with your id!"
} });
} else {
if (res.user_password == password_sha256) {
console.log("user found");
callback(err, { meta: { code: 200 },
token: password_sha256,
type: 1 });
return;
} else if (res.owner_password == password_sha256) {
console.log("owner found");
callback(err, { meta: { code: 200 },
token: password_sha256,
type: 0 });
} else {
console.log("user not found");
callback(err, { meta: {
code: 403,
error_message: "There are no users with your password!"
} });
}
}
});
}
I post some data using this function:
router.post('/api/login', (req, res) => {
db.getUserToken(req.body, function(err, result) {
console.log(result);
if (result.error) {
return res.status(403).send(result);
} else {
return res.status(200).send(result);
}
});
});
And then getUserToken found, for example, user, so I have "user found" in console log, but callback function in /api/login not working. Where is my error and how can I fix them?
Instead of callback, you can return a Promise, either native or using an external library like Kris Kowal Q
var Q = require('q');
function getUserToken(data) {
var deferred = Q.defer();
var password_sha256 = sha256(data.password);
getAppById(data.app_id).then(function(res) {
if (!res) {
deferred.reject("There are no app with your id!");
} else {
if (res.user_password == password_sha256) {
deferred.resolve({
token: password_sha256,
type: 1
});
} else if (res.owner_password == password_sha256) {
deferred.resolve({
token: password_sha256,
type: 0
});
} else {
console.log("user not found");
deferred.reject("There are no users with your password!");
}
}
})
.catch(function(error) {
deferred.reject(error);
});
return deferred.promise;
}
Then simply process or catch error when you post data
router.post('/api/login', (req, res) => {
db.getUserToken(req.body)
.then(function(result) {
res.status(200).send(result);
})
.catch(function(error) {
res.status(403).send(error);
});
});
Instead of using callback(err, data) you should use callback(null,data).This will give you required output.
I have problem with my node.js bot to roulette. Bot is fully set up but when I launching it, it gives me error "Bot stopped with code null". Can someone help me to fix it?
Here is the error screenshot: http://i.imgur.com/zfZoMD4.png
Code:
function login(err, sessionID, cookies, steamguard) {
if(err) {
logger.error('Auth error');
logger.debug(err);
if(err.message == "SteamGuardMobile") {
account.twoFactorCode = SteamTotp.generateAuthCode(account.shared_secret);
logger.warn('Error in auth: '+account.twoFactorCode);
setTimeout(function() {
community.login(account, login);
}, 5000);
return;
}
process.exit(0);
}
logger.trace('Sucesfully auth');
account.sessionID = sessionID;
account.cookies = cookies;
community.getWebApiKey('csgobananas.com', webApiKey);
community.startConfirmationChecker(10000, account.identity_secret);
}
function webApiKey(err, key) {
if(err) {
logger.error('Cant make apikey')
logger.debug(err);
process.exit(0);
return;
}
account.key = key;
logger.trace('API key bot '+account.accountName+' '+account.key);
offersSetup();
community.loggedIn(checkLoggedIn);
}
function offersSetup() {
logger.trace('Loaded steam-tradeoffers');
offers.setup({
sessionID: account.sessionID,
webCookie: account.cookies,
APIKey: account.key
});
}
function checkLoggedIn(err, loggedIn, familyView) {
if((err) || (!loggedIn)) {
logger.error('We arent logged in')
process.exit(0);
} else {
logger.trace('Logged in');
account.auth = true;
bot_manager.js code:
var forever = require('forever-monitor');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
database: 'placeholder',
host: 'placeholder',
user: 'placeholder',
password: 'placeholder'
});
query('SELECT * FROM `bots`', function(err, row) {
if((err) || (!row.length)) {
console.log('Failed request or empty bot table');
console.log(err);
return process.exit(0);
}
console.log('List of bots:');
row.forEach(function(itm) {
console.log('Launching bot# '+itm.id);
var bot = new (forever.Monitor)('bot.js', {
args: [itm.id]
});
bot.on('start', function(process, data) {
console.log('Bot with ID '+itm.id+' started');
});
bot.on('exit:code', function(code) {
console.log('Bot stopped with code '+code);
});
bot.on('stdout', function(data) {
console.log(data);
});
bot.start();
});
});
function query(sql, callback) {
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
console.info('Database connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}