Search code examples
javascriptnode.jseventscsvfirst-class-functions

Not Understanding usage of First-class function and csv module events in node.js example


I'm having some trouble understanding the code in this code snippet. I've been commenting and researching, but I've run into a snag. Well I've run into two snags, but one has to do with an outdated csv library. Here is the code snippet:

var csv2console = function(csvfile, headers) {
    console.log(headers.join("\t"));

    csv()
    .from.path(csvfile)
    .on('record', function(row, index) {
        var shares = Math.round(marketCapFloat(row[2])/row[3], 0);
        var eps = (row[3]/row[4]).toFixed(3);
        var earnings = accounting.formatMoney(eps * shares);
        outrow = row.concat([shares, eps, earnings]);
        console.log(outrow.join("\t"));
    });
};

var buildfn = function(csvfile, headers) {
    var response2console = function(result, response) {
        if (result instanceof Error) {
            console.error('Error: ' + util.format(response.message));associated with the error?
        } else {
            console.error("Wrote %s", csvfile);
            fs.writeFileSync(csvfile, result);
            csv2console(csvfile, headers);
        }
    };
    return response2console;
};

var marketResearch = function(symbols, columns, csvfile, headers) {
    symbols = symbols || SYMBOLS_DEFAULT;
    columns = columns || COLUMNS_DEFAULT;
    csvfile = csvfile || CSVFILE_DEFAULT;
    headers = headers || HEADERS_DEFAULT;
    var apiurl = financeurl(symbols, columns);
    var response2console = buildfn(csvfile, headers);
    rest.get(apiurl).on('complete', response2console);
};

My main problem with this code snippet has to do with the second function. I get that they are passing a function back to the calling function, but I don't understand why there are two paramaters for the response2console function, yet no parameters ever seem to be passed to the function when it is used in the market research function. Are these default parameters or dummy parameters? They seem to be being used, so the parameters need to be taken from somewhere? Do they correspond with csvfile and headers?

My second problem has to do with the .on() function. I looked at the csv documentation, but I couldn't find any commentary on what this does. They seem to only use it. After some more research, I've come to the conclusion that this is a javascript or node.js event function, and that 'record' is a type of event. But I can't find doc anywhere what this 'record' event is. Any suggestions on where to look or any help in the matter would be appreciated.

csv doc: http://www.adaltas.com/projects/node-csv/from.html


Solution

  • yet no parameters ever seem to be passed to the function when it is used in the market research function

    That's because it is not called in the marketResearch function. Instead, it is passed to .on(), registering it as an event handler to be called with a complete event.

    My second problem has to do with the .on() function. I looked at the csv documentation, but I couldn't find any commentary on what this does

    The on method is not part of the csv module, but of the rest module. It seems to issue an HTTP request, calling back the response2console function with the received file and http headers. Oh wait, you mean the other use.

    Yes, your conclusion is correct. This is documented here in the introduction:

    Events:

    The library extends Node EventEmitter class and emit all the events of the Writable and Readable Stream API. Additionally, the useful “records” event is emitted.

    • record
      Emitted by the stringifier when a new row is parsed and transformed. The data is the value returned by the user transform callback if any. Note however that the event won’t be called if transform returns null since the record is skipped. The callback provides two arguments. row is the CSV line being processed (an array or an object) and index is the index number of the line starting at zero