访问Javascript对象 - Node.js的范围问题

时间:2016-05-03 10:10:20

标签: javascript node.js scope

我想使用Node守护程序定期从邮箱中获取邮件。对连接方法的调用是在app.js中进行的。

我用来连接到我的邮箱(mail.js)的javascript文件:

var imap = new Imap({
    user: 'xxxx@hotmail.com',
    password: config.get.gmail_password,
    host: 'xxxxx',
    port: 993,
    tls: true
});

var fetchMail = function()
{
    console.log('Connection');
    imap.connect();
};

//fetchMail();

imap.once('ready', function() {
   console.log('Ready'); 

   imap.search([ 'UNSEEN', ['FROM', 'xxxx'] ], function(err, results)
   {
       // Do Stuff
   }

exports.fetchMail = fetchMail;

如果我直接从fetchMail()使用mail.js,一切都很好。

但是,当我尝试从app.js

调用它时
var mail = require('./js/mail');
mail.fetchMail() 

然后,该方法保留在fetchMail()的{​​{1}}函数中,mail.js永远不会被触发。

我想这是imap.once('ready', function())imap var的范围问题。

我该如何解决这个问题?

修改

我以一种我不喜欢的方式解决了这个问题。我在mail.js函数中编写了与imap var相关的所有内容。

请不要犹豫,写一个更有效的答案。

2 个答案:

答案 0 :(得分:1)

每次连接时都需要绑定事件。所以这样:

var fetchMail = function()
{
    console.log('Connection');

    imap.once('ready', function() {
      console.log('Ready');         
      imap.search([ 'UNSEEN', ['FROM', 'xxxx'] ], function(err, results)
      {
        // Do Stuff
      }
    }
    imap.connect();
};

答案 1 :(得分:0)

方法和想法很棒。您只需要更改mail.js文件的语法以返回模块。换句话说,当你做

var mail = require('./js/mail');

你期望在邮件变量中做什么?

你可能需要改变逻辑,但试试这个:

var MailHandler = function () {}

var imap = new Imap({
    user: 'xxxx@hotmail.com',
    password: config.get.gmail_password,
    host: 'xxxxx',
    port: 993,
    tls: true
});

MailHandler.init = function(){
  imap.once('ready', function() {
     console.log('Ready'); 

     imap.search([ 'UNSEEN', ['FROM', 'xxxx'] ], function(err, results)
     {
         // Do Stuff
     }
  }
}

MailHandler.fetchMail = function()
{
  console.log('Connection');
  imap.connect();
};

//fetchMail();

module.exports = new MailHandler()