Florin Pop Florin Pop - 2 months ago 19
Node.js Question

Nodejs readline callback

I am studying callbacks, and for some reason I can't get it right...
I want to read a file, and save it's data to a global variable to play with later.

Here is what I have so far:

var fs = require("fs");
var readline = require("readline");
var i = 0;
var total = 66; //put the total foldernames or total images (same number)
var folder_names = [];
var data = [];

lineReader = readline.createInterface({
input: fs.createReadStream("folder-names and data.txt")
});


lineReader.on('line', function(line, dataCollector) {
if(i<66)
folder_names.push(line);
else
data.push(line);

dataCollector(folder_names, data);
i++;
});

var dataCollector = function(folder_names, data) {
//console.log(folder_names);
}

console.log(folder_names[0]); //should have a value now.


What is wrong? I get:
dataCollector is not a function

Answer

You're shadowing the dataCollector identifier here:

lineReader.on('line', function(line, dataCollector) {

That declares dataCollector as the second argument to your callback, shadowing (hiding) the identifier at the top level of your script.

The line event doesn't document any second argument for its callback, so it should look like this:

lineReader.on('line', function(line) {

Re your extension of the question:

console.log(folder_names[0]); //should have a value now.

No, it shouldn't. Why: How do I return the response from an asynchronous call?

In your case, you probably want to do your console.log in an close event handler:

lineReader
    .on('line', function(line) {
        if(i<66)
            folder_names.push(line);
        else
            data.push(line);

        dataCollector(folder_names, data);
        i++;
    })
    .on('close', function() {
        console.log(folder_names[0]); // has its values now
    });