2012-03-26 134 views
1

因此,我試圖通過node.js發送自己的IP地址,到目前爲止都出現空手。到目前爲止,我的代碼如下所示:發送郵件的IP地址與node.js

var exec = require("child_process").exec; 
var ipAddress = exec("ifconfig | grep -m 1 inet", function (error, stdout, stderr) { 
    ipAddress = stdout; 
}); 
var email = require('nodemailer'); 

email.SMTP = { 
    host: 'smtp.gmail.com', 
    port: 465, 
    ssl: true, 
    user_authentication: true, 
    user: '[email protected]', 
    pass: 'mypass' 
} 

email.send_mail({ 
    sender: '[email protected]', 
    to: '[email protected]', 
    subject: 'Testing!', 
    body: 'IP Address of the machine is ' + ipAddress 
    }, 
    function(error, success) { 
     console.log('Message ' + success ? 'sent' : 'failed'); 
       console.log('IP Address is ' + ipAddress); 
       process.exit(); 
    } 
); 

到目前爲止,這是發送電子郵件,但它從來沒有插入的IP地址。它將適當的IP地址放在我可以看到的控制檯日誌中,但無法通過電子郵件發送。任何人都可以幫助我看看我在代碼中做錯了什麼?

+0

爲什麼要使用「執行」,而不是'os.networkInterfaces'這是跨操作系統? 來源:http://nodejs.org/docs/latest/api/os.html#os_os_networkinterfaces – seppo0010 2012-03-26 20:48:58

回答

0

這是因爲send_mail函數在exec已經返回ip之前啓動。

所以只要開始發送郵件一旦exec已經返回了IP。

這應該工作:

var exec = require("child_process").exec; 
var ipAddress; 
var child = exec("ifconfig | grep -m 1 inet", function (error, stdout, stderr) { 
    ipAddress = stdout; 
    start(); 
}); 
var email = require('nodemailer'); 

function start(){ 

    email.SMTP = { 
     host: 'smtp.gmail.com', 
     port: 465, 
     ssl: true, 
     user_authentication: true, 
     user: '[email protected]', 
     pass: 'mypass' 
    } 

    email.send_mail({ 
     sender: '[email protected]', 
     to: '[email protected]', 
     subject: 'Testing!', 
     body: 'IP Address of the machine is ' + ipAddress 
     }, 
     function(error, success) { 
      console.log('Message ' + success ? 'sent' : 'failed'); 
        console.log('IP Address is ' + ipAddress); 
        process.exit(); 
     } 
    ); 
} 
+0

是的,這工程就像一個魅力!非常感謝,因爲您可能知道我真的不知道我在做什麼node.js :-) – noiz77 2012-03-26 07:53:50

+0

不客氣!每一個開始都很難:D – stewe 2012-03-26 08:01:42