Node.JS-节点PowerShell返回值

Node.JS-节点PowerShell返回值,node.js,Node.js,我正在使用来自的节点powershell模块 我试图从函数返回数据并将其分配给变量$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('

我正在使用来自的节点powershell模块

我试图从函数返回数据并将其分配给变量$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();

但是它没有分配数据。

您没有看到数据,因为您的return语句将数据返回给了错误的调用者:)
PS('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
参数,但error-first回调是节点中的惯例。如果模块支持,您应该添加
PS.on('error')…

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
});