访问Javascript对象-Node.js的作用域问题

Access Javascript object - Scope issue with Node.js

本文关键字:作用域 问题 js -Node Javascript 对象 访问      更新时间:2023-09-26

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

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

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;

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

然而,当我尝试从app.js:调用它时

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

然后,该方法停留在mail.jsfetchMail()函数中,并且imap.once('ready', function())从不被触发。

我想这是mail.jsimap变量的范围问题。

我该怎么解决这个问题?

编辑

我用一种我不喜欢的方式解决了这个问题。我在fecthMail()函数中编写了与imap-var相关的所有内容。

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

每次连接时都需要绑定事件。大致如此:

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();
};

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

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

您希望在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()