0

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 ?

7
  • 1
    Nowhere in this code do you use pushArray (as a callback or otherwise). We have no way of telling why the second argument to it is not an object with a forEach property. Commented Oct 10, 2016 at 13:05
  • How do you call pushArray? Commented Oct 10, 2016 at 13:06
  • added some calling code. Again the show Data works with that Commented Oct 10, 2016 at 13:10
  • @user3732793 — The "calling code" still doesn't mention the pushArray function. Commented Oct 10, 2016 at 13:12
  • You need a real minimal reproducible example Commented Oct 10, 2016 at 13:12

1 Answer 1

1
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);
Sign up to request clarification or add additional context in comments.

1 Comment

oh man ...you are absolutely right there is a typo...notepad is probably not a good editor....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.