程序正在退出,但该功能仍在节点js

时间:2018-04-19 12:28:48

标签: node.js callback imap

我的程序在功能完成之前退出。我也使用了回调,但功能仍在退出。

    var Imap = require('imap'),
    inspect = require('util').inspect;
    var MailParser = require("mailparser").MailParser;

    var mail, otp, imap;
    var fullPattern = new RegExp('<span.*>[0-9]{6}</span>');
    var otpPattern = new RegExp('[0-9]{6}');

    function setEmail(email, password, mailType){
        if(mailType == 'outlook')
            mail = outlook;
        else
            mail = gmail;
        mail.email = email;
        mail.username = email;
        mail.password = password;
    }

    function setIMAP(){
          imap = new Imap({
              user: mail.email,
              password: mail.password,
              host: mail.imap.host,
              port: 993,
              tls: true
          });
    }

    function read(email, password, mailType){
        setEmail(email, password, mailType);
        setIMAP();

        readMail(function(err, otp){
            if(err){
                console.log(err);
                return null;
            }
            else{
                if(otp != undefined){
                    console.log('Final OTP : ' + otp);
                    return otp;
                }
                else{
                    console.log('Sorry No OTP found ');
                    return null;
                }
            }
        });
    }

    function openInbox(cb) {
      imap.openBox('INBOX', false, cb);
    }

    function readMail(callback){

        imap.once('ready', function(){
            openInbox(function(err, box){
                if(err) throw err;
                imap.search(['UNSEEN'], function(err, results){

                    if(results){
                        console.log('No new messages');
                        callback('NO_MSG', null);
                    }else{

                        imap.setFlags(results, ['\\Seen'], function(err) {
                            if (!err) {
                                console.log("marked as read");
                            } else {
                                console.log(JSON.stringify(err, null, 2));
                            }
                        });

                        var f = imap.fetch(results, {
                            bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)', 'TEXT'],
                            struct: true
                        });

                f.on('message', function(msg, seqno){
                    var msgHeaders = '', msgText = '';
                    console.log("Processing msg #" + seqno);

                        var parser = new MailParser();

                        parser.on('data', data => {
                            msgText = data.text;
                            if (data.type === 'text') {
                                var spanTag = fullPattern.exec(data.text);
                                console.log('Span : ' + spanTag);
                                var currOtp = otpPattern.exec(spanTag);
                                if(spanTag != '' && spanTag != null && spanTag != 'null')
                                     otp = currOtp;
                                console.log('OTP : ' + otp);
                            }
                         });

                        msg.on("body", function(stream, info) {
                            stream.on("data", function(chunk) {
                                parser.write(chunk.toString('utf8'));
                            });


                        });

                        msg.once("end", function() {
                            console.log('Ending ' + seqno);
                            parser.end();
                        });
                });

                f.once('error', function(err) {
                  console.log('Fetch error: ' + err);
                });

                f.once('end', function() {
                  console.log('Done fetching all messages!');
                  imap.end();
                });
            }

        });
    });
});

imap.once('error', function(err) {
  console.log(err);
});

imap.once('end', function() {
  console.log('Connection ended');
  console.log('Main OTP : ' + otp);
  callback(null, otp);
});

imap.connect();

}

    function run(){
      var finalOtp = read('*******@******.com', '*****', 'outlook');
      console.log(finalOtp);
    }

我能够阅读邮件并获得所需的OTP值。但该程序正在退出,但该功能仍在执行中。 run()函数通过打印未定义但在第二个finalOTP获得正确值后退出。我无法理解如何停止该功能一般退出。

假设我在read()调用语句下面没有代码。该功能直接退出,但稍后会打印一些数据。

1 个答案:

答案 0 :(得分:0)

read函数不能同步,而它的依赖项readEmail是异步的。您需要接受read上的回调,并在完成处理而不是返回值时进行调用。

read看起来像这样:

function read(email, password, mailType, callback) {
    setEmail(email, password, mailType);
    setIMAP();

    readMail(function (err, otp) {
        if (err) {
            //console.log(err);
            //return null;
            return callback(err);
        }
        if (otp !== undefined) {
            console.log('Final OTP : ' + otp);
            //return otp;
            return callback(null, otp);
        }
        else {
            console.log('Sorry No OTP found ');
            return callback(null, null);
        }
    });
}

然后在底部你可以这样做:

function run(){
    var finalOtp = read('*******@******.com', '*****', 'outlook', function(err, otp){
        if(err){
            throw err

        }
        console.log(otp);  //OTP might be null if it was not found            
    });
}