user3732793 user3732793 - 1 month ago 8
Node.js Question

node js TypeError: callBack is not a function

Here two functions

function pushArray(data, array){
var index = -1;
array.forEach(function(item) {
if(item.name === data.name) {
index = array.indexOf(item);
console.log('found existing item at ' + index);
}
});
if(index >= 0){
array[index] = newItem;
}else {
array.push(newItem);
}
}

function showData(data, array){
try {
if(data){
console.log('data \n');
console.log(data.toString());
console.log(array);
}
} catch (error) {
console.log("Showing data caused error: " + error);
}
}


This is how the callbacks are called

fsReadFile(csvPath1, pushArray. array1);
fsReadFile(csvPath1, showData, array1);

function fsReadFile (filePath, callBack, array) {
fs.readFile(filePath, function(err, data) {
if(err) {
console.error(err);
}
callBack(data, array);
});
}


the show data shows either data and array when send as callback but the pushArray doesn't work as callback as node js complains

array.forEach(function(item) {
^

TypeError: Cannot read property 'forEach' of undefined


Is that more an callback or array issue ? If anyone could explain the root cause ?

Answer
fsReadFile(csvPath1, pushArray(). array1);

You are calling pushArray immediately, with no arguments (so array is undefined), and the return value is passed as the second argument. Don't call it there.

Then you have a typo where you have a . instead of a comma (so you try to read the array1 property of the return value of pushArray() and don't pass a third argument at all).

fsReadFile(csvPath1, pushArray, array1);