0

I'm trying to create a function that'll search for a process by name in node.js. Here's my function:

function findProcess(name)
{
    //Global var so the scope of the function can reach the var
    var toReturn;

    ps.lookup(
    {
        command: name
    }, function(err, resultList)
    {
        if(err)
        {
            throw new Error(err);
        }

        if(resultList.length > 0)
        {
            toReturn = true;
            console.log("running");
        }
        else
        {
            toReturn = false;
        }
    });

    console.log(toReturn);
}

The problem here is toReturn doesn't ever get set to true, even if the console outputs running. I've trued declaring toReturn as a public variable at the top of my code, but that doesn't do the trick. Does anyone know why my issue is?

Paul
  • 139,544
  • 27
  • 275
  • 264
Ubspy
  • 15
  • 5

1 Answers1

0

Add a second parameter to findProcess(), a callback function which you will call from inside the ps.lookup() callback. Pass any data you need to this callback, in this case your boolean value. For example:

function findProcess( name, callback ) {
    ps.lookup({
        command: name
    }, function( err, resultList ) {
        if( err ) throw new Error( err );
        callback( resultList.length > 0 );
    });
}

findProcess( 'something', function( isRunning ) {
    console.log( 'is running?', isRunning );
});
Michael Geary
  • 28,450
  • 9
  • 65
  • 75