Eamorr
Eamorr

Reputation: 10012

node.js "undefined" mysteriously appears

I have the following node.js files:

//test.js:
var hash=require('./hash');
var sys=require('sys');

sys.puts(hash.hash("asdf","asdf"));

and

//hash.js:
var exec=require('child_process').exec;
var sys=require('sys');

exports.hash=function(data,hash_type){
        exec('pwd',function callback(error,stdout,stderr){
                sys.puts(stdout);
        });
}

When I do node test.js, I get the following output:

eamorr@Compaq6000:~/Desktop/simple-hash$ node test.js 
undefined
/home/hynese/Desktop/nodejs-simple-hash

Why am I getting "undefined"??? I'm really stuck here...

Any help is greatly appreciated.

Many thanks in advance,

Upvotes: 0

Views: 767

Answers (1)

davin
davin

Reputation: 45525

Change:

sys.puts(hash.hash("asdf","asdf"));

to just:

hash.hash("asdf","asdf");

You're outputting the return value of hash.hash, although since you didn't provide a return value, the language returns undefined, which is then outputted to the screen. You already output the result of the system command in the callback, so you don't need another sys.puts.

As a side note, you probably don't need to name that callback function callback.

Upvotes: 3

Related Questions