4

I am using a node-powershell module from https://www.npmjs.com/package/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 
});

I am trying to return data from a function and assign it to a variable $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();

But it does not assign it.

1 Answer 1

3

You are not seeing the data because your return statement is returning it to the wrong caller :) PS.on('output' ... is registering a callback function for an event. The provided function will then be called by the event emitter when the event is raised. Therefore, the value returned by this callback is actually being returned to the event emitter, who doesn't care about your return value, rather than the caller of getData.

To correct the issue, you should provide a callback of your own, try this:

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

As an aside, you may not need the err parameter, but error-first callbacks are the convention in node. You should probable add PS.on('error' ... if the module supports it...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.