[英]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.