Node.JS – Node-PowerShell返回值

我使用https://www.npmjs.com/package/node-powershell中的node-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 }); 

我想从一个函数返回数据,并将其分配给一个variables$ 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(); 

但它不分配它。

你没有看到数据,因为你的返回语句将它返回给错误的调用者: PS.on('output' ...正在为一个事件注册一个callback函数,当提供的函数被事件发送器调用时事件发生,因此这个callback函数返回的值实际上是返回给事件发射器的,它不关心你的返回值,而不是getData的调用者。

要纠正这个问题,你应该提供一个你自己的callback,试试这个:

 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参数,但是错误优先callback是节点中的约定。 你应该很可能添加PS.on('error' ...如果模块支持它…