[英]Access Javascript object - Scope issue with Node.js
I'd like to fetch mail from a mailbox regularly using a Node daemon. 我想使用Node守护程序定期从邮箱中获取邮件。 The call to the connection method is made in
app.js
. 对连接方法的调用是在
app.js
。
The javascript file I use to connect to my mailbox ( mail.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;
If I use fetchMail()
directly from mail.js
, everything is fine. 如果我直接从
mail.js
使用fetchMail()
,一切都很好。
However, when I try to call it from app.js
: 但是,当我尝试从
app.js
调用它时:
var mail = require('./js/mail');
mail.fetchMail()
Then, the method stay in the fetchMail()
function from mail.js
and the imap.once('ready', function())
is never triggered. 然后,在该方法中停留
fetchMail()
从函数mail.js
和imap.once('ready', function())
永远不会触发。
I guess it is a scope issue with the imap
var in mail.js
. 我想这是
mail.js
imap
var的范围问题。
How can I fix this? 我怎样才能解决这个问题?
EDIT 编辑
I solved this in a way I don't like. 我以一种我不喜欢的方式解决了这个问题。 I wrote everything's related to the imap var inside the
fecthMail()
function. 我在
fecthMail()
函数中编写了与imap var相关的所有内容。
Please, do not hesitate to write a more efficient answer to this. 请不要犹豫,写一个更有效的答案。
You would need to bind the event every time you connect. 每次连接时都需要绑定事件。 So like so:
所以这样:
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();
};
The approach and idea is great. 方法和想法很棒。 All you need is to change the syntax of mail.js file to return a module.
您只需要更改mail.js文件的语法以返回模块。 In another words when you do
换句话说,当你这样做
var mail = require('./js/mail');
what do you expect to be in the mail variable? 你期望在邮件变量中做什么?
You might need to change logic around, but try this: 你可能需要改变逻辑,但试试这个:
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.