2016-02-12 43 views
1

我使用的是節點的PowerShell模塊從https://www.npmjs.com/package/node-powershell的Node.js - 節點PowerShell的返回值

var shell = require('node-powershell'); 
PS = new shell('echo "node-powershell is awesome"'); 
PS.on('output', function(data){ 
    console.log(data); 
}); 
PS.on('end', function(code) { 
    //optional callback 
    //Do Something 
}); 

我試圖從一個函數返回的數據,並將其分配給一個變量$ returneddata:

function getData() 
{ 
var shell = require('node-powershell'); 
PS = new shell('echo "node-powershell is awesome"', {debugMsg: false}); 
PS.on('output', function(data){ 
    return data; 
}); 
PS.on('end', function(code) { 

}); 

} 

var $returneddata = getData(); 

但它不會給它。

回答

1

因爲你return語句返回給調用者錯誤:) PS.on('output' ...正在註冊一個回調函數爲一個事件你沒有看到的數據。提供的功能將在事件發生時由事件發射器調用。因此,此回調返回的值實際上將返回給事件發射器,它不關心您的返回值,而不是getData的調用者。

要解決的問題,您應該提供自己的回調,試試這個:

function getData(callback) { 
    var shell = require('node-powershell'); 
    PS = new shell('echo "node-powershell is awesome"', {debugMsg: false}); 
    PS.on('output', function(data){ 
     return callback(null, data); 
    }); 
    PS.on('end', function(code) { 

    }); 
} 

getData(function onGetData(err, data) { 
    // do stuff with the returned data here 
}); 

順便說一句,你可能不需要err參數,但誤差第一回調是在節點公約。如果模塊支持它,您應該添加PS.on('error' ... ...