Node.js“未定义”神秘地出现
我有以下 node.js 文件:
//test.js:
var hash=require('./hash');
var sys=require('sys');
sys.puts(hash.hash("asdf","asdf"));
并且
//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);
});
}
当我执行 node test.js
时,我得到以下输出:
eamorr@Compaq6000:~/Desktop/simple-hash$ node test.js
undefined
/home/hynese/Desktop/nodejs-simple-hash
为什么我得到“未定义”???我真的被困在这里...
非常感谢任何帮助。
预先非常感谢,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将:更改
为 just:
您正在输出
hash.hash
的返回值,尽管由于您没有提供返回值,所以语言返回 undefined,然后将其输出到屏幕。您已经在回调中输出了系统命令的结果,因此您不需要另一个sys.puts
。附带说明一下,您可能不需要将该回调函数命名为
callback
。Change:
to just:
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 anothersys.puts
.As a side note, you probably don't need to name that callback function
callback
.