[英]Access Javascript object - Scope issue with Node.js
我想使用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()
然后,在该方法中停留fetchMail()
从函数mail.js
和imap.once('ready', function())
永远不会触发。
我想这是mail.js
imap
var的范围问题。
我怎样才能解决这个问题?
编辑
我以一种我不喜欢的方式解决了这个问题。 我在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');
你期望在邮件变量中做什么?
你可能需要改变逻辑,但试试这个:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.