Node.js callback not working - node.js

I have the following two Node.js files:
//test.js
var hash=require('./hash');
var sys=require('sys');
hash.hash("asdf",function(param){
sys.puts(param);
});
and
//hash.js:
var exec=require('child_process').exec;
var sys=require('sys');
exports.hash=function(data,callback){
exec("./a.out "+data,function callback(error,stdout,stderr){
callback(stdout);
});
}
As you can see, I'm trying to make stdout available in test.js
Trouble is, when I run node test.js, I get the following error:
eamorr#Compaq6000:~/Desktop/simple-hash$ node test.js
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
RangeError: Maximum call stack size exceeded
Anyone got any ideas as to what I might be doing wrong?
Many thanks in advance,
Edit: solution: rename the inner "callback" to "callback2" or something else... Thanks to Idan K for pointing this out.

When you call exec you are naming what should be an anonymous function, callback. This has the same name as the second argument to hash, hence the recursion.

Related

Catching all unhandled errors in Gulp

Our Gulp build process fails for some new developers like this:
events.js:85
throw er; // Unhandled 'error' event
^
Error: EMFILE, open '[some filename]'
at Error (native)
The solution is to run:
ulimit -n 2048
So I'd like to catch the EMFILE error and replace it with a friendlier message. However, even wrapping the entire gulpfile.js in a try/catch doesn't seem to contain it.
It turns out that wrapping try/catch around everything doesn't work because the errors happen after (all) the code is executed. Injecting an error handler into every single pipe works:
function onError(e) {
if (e.code === 'EMFILE') {
console.error('Too many open files. You should run this command:\n ulimit -n 2048');
process.exit(1);
}
gutil.log(e.message);
process.exit(1);
}
...
var result = bundler.bundle();
result = result
.on('error', onError)
.pipe(source(name))
.pipe(buffer());

Error handling in Node.js for calling a function with wrong name

I am requiring a module and saving it in a variable. But when I call a module function by wrong name, it does not throw any error or consoles any error. How do I make this throw error?
var module = require('../pre_process/' + preProcessFolder + '/' + preProcessModule);
// module -> { XYZ: [Function] }
//Following does not throw error and doesn't console anything.How to handle/debug this error
module['XY'](result, userId)
.then(function(recData) {
})
I am using q library for promise.
So you want to check if a function (provided by a modul) exists.
You could use try like the example here:
Javascript check if function exists

The strange Node.js error after starting script

I use Node.js.
My server js script I run such:
node chat_server.js
After I get errors messages in terminal CentOS:
Express server listening on port undefined in development mode.
+ User undefined connected node_redis: no callback to send error: ERR wrong number of arguments for 'sadd' command
/home/who/public_html/node/node_modules/redis/index.js:582
throw err;
^ Error: ERR wrong number of arguments for 'sadd' command
at ReplyParser. (/home/who/public_html/node/node_modules/redis/index.js:317:31)
at ReplyParser.emit (events.js:95:17)
at ReplyParser.send_error (/home/who/public_html/node/node_modules/redis/lib/parser/javascript.js:296:10)
at ReplyParser.execute (/home/who/public_html/node/node_modules/redis/lib/parser/javascript.js:181:22)
at RedisClient.on_data (/home/who/public_html/node/node_modules/redis/index.js:547:27)
at Socket. (/home/who/public_html/node/node_modules/redis/index.js:102:14)
at Socket.emit (events.js:95:17)
at Socket. (_stream_readable.js:748:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:410:10)
Excuse me, but I do not understand the reason of these errors.
On what I should get attention and how fix it?
For example, I use command redis SADD: redis_cli.sadd( "user.friend:" + currentIdUser, data.idUser);
I have done a experiment, created a new text script:
var redis = require("redis");
var client = redis.createClient();
client.on("error", function (err) {
console.log("Error " + err);
});
client.sadd("users","naveen",function(err,reply){
console.log('Ok');
if(err)
throw err;
return reply;
});
It have given me in console: OK. It mean, that all works fine.
I think in my code:
redis_cli.sadd("userslist", currentIdUser);
the variable currentUser is simply empty or undefined. It gives me the next errors.
Problem was at my script in line:
redis_cli.sadd("userslist", currentIdUser);
The variable is undefined. It calls error redis.
Thank you all for help.

Calling a module function inside a Nodejs callback

I have a module that writes to a log file. (coffeescript sorry, but you get the idea!)
require = patchRequire(global.require)
fs = require('fs')
exports.h =
log: ()->
for s in arguments
fs.appendFile "log.txt", "#{s}\n", (e)->
if (e) then throw e
It works file when I call it directly. But when I call it from a callback, for example casperjs start event:
h = require('./h').h
casper = require('casper').create()
casper.start "http://google.com", ()->
h.log("hi")
casper.run()
... I always get this or similar "undefined" TyepError:
TypeError: 'undefined' is not a function (evaluating 'fs.appendFile("log.txt", "" + s + "\n", function(e) {
if (e) {
throw e;
}
})')
Googling this doesn't give many clues!
CasperJS runs on PhantomJS (or SlimerJS) and uses its modules. It is distinct from nodejs. PhantomJS' fs module doesn't have an appendFile function.
Of course you can use fs.write(filepath, content, 'a'); to append to a file if used in casper. If you still want to use your module both in casper and node then you need to write some glue code like
function append(file, content, callback) {
if (fs.appendFile) {
fs.appendFile(file, content, callback);
} else {
fs.write(file, content, 'a');
callback();
}
}
I think the problem is with the coffeescript. Try using a splat parameter instead of relying on the arguments object.
log(statements...)
If that doesn't work, you might need to look at the javascript output or try the same thing in plain JavaScript and see if you get the same error.

Node.js Callback Failing - Function pass Variables with Callback

I'm new to Node.js and I'm struggling to get a callback to work. I have the following function call:
memberPhotoPath(dbResults[i].userid2,dbResults[i].userid2Gender,'small',dbResults[i].userid2PhotoName,dbResults[i].userid2PhotoVerified,false,function(path) {
console.log(path);
});
and the following function:
function memberPhotoPath(userid,gender,photoSize,photoName,photoVerification,border,callback) {
if(photoVerification) {
callback('http://www.datingimages.co/online-dating/dating-photos/'+userid+'/'+userid+'-'+photoSize+'-'+photoName+'.jpg');
}else{
if(border) {
if(gender) {
callback('http://www.datingimages.co/online-dating/dating-website/default-female-image-'+photoSize+'.png');
}else{
callback('http://www.datingimages.co/online-dating/dating-website/default-male-image-'+photoSize+'.png');
}
}else{
if(gender) {
callback('http://www.datingimages.co/online-dating/dating-website/default-female-image-'+photoSize+'-noborder.png');
}else{
callback('http://www.datingimages.co/online-dating/dating-website/default-male-image-'+photoSize+'-noborder.png');
}
}
}
}
I get the following error in Node.js:
TypeError: undefined is not a function
at memberPhotoPath (/etc/node/index.js:315:5)
at /etc/node/index.js:223:21
at memberPhotoPath (/etc/node/index.js:315:5)
at /etc/node/index.js:214:9
at Array.forEach (native)
at /etc/node/index.js:208:34
at Query._callback (/etc/node/index.js:287:9)
at Query.Sequence.end (/usr/lib/node_modules/mysql/lib/protocol/sequences/Sequence.js:75:24)
at Query._handleFinalResultPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:143:8)
at Query.EofPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:127:8)
Any advice on what I'm doing wrong?
thankyou
I have just run this code in the chrome console and it works fine. The error must be somewhere down the line. With asynchronous functions it is sometimes not possible to track the exact stack trace. I advise you brace yourself and go through your other code again

Resources