ChriSxStyles
ChriSxStyles

Reputation: 115

Nodejs function scope

Can someone help me understand why the following doesn't work? I'm trying to wrap my head around javascript and nodejs. I just want the function to return the hash. I may not be understanding function scope correctly.

function generateHash() {

    var hash = '';

    var toHash = function(stdout){
        hash = new Buffer(stdout).toString('base64');
        //console.log(hash);
        return hash;
    };

    exec("date +%Y-%m-%d", function(err, stdout, stderr){
        var todaysDate = stdout.trim();
        toHash(todaysDate);
    });

};

console.log(generateHash());

The result I get is undefined.

Upvotes: 0

Views: 172

Answers (1)

joozek
joozek

Reputation: 2211

Your function doesn't return anything - hence undefined.

In node there's a convention about asynchronous execution - functions should accept callback as their last argument and this callback is passed error and result as arguments. You can see it in your example:

exec("date +%Y-%m-%d", function(err, stdout, stderr){
        var todaysDate = stdout.trim();
        toHash(todaysDate);
    });

exec isn't returning anything - instead it accepts aforementioned callback. This callback is called when the action is completed and is given either an error or all the other arguments. If you want to call async function you have to be async too! so you should change your generateHash function to be async.

You could also spot that your callback to exec doesn't do nor return anything it just calls toHash - dead ends are often symptoms of problems with code.

Your async code could look like this:

function generateHash(callback) {
    var toHash = function(stdout){
        return new Buffer(stdout).toString('base64');
    };

    exec("date +%Y-%m-%d", function(err, stdout, stderr){
        var todaysDate = stdout.trim();
        if(err) {
            return callback(err);
        }
        callback(null, toHash(todaysDate));
    });

};

generateHash(function(err, hash) {
    console.log(hash);
});

Upvotes: 2

Related Questions