简体   繁体   中英

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

You're shadowing the dataCollector identifier here:

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

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

The line event doesn't document that it provides a second argument to 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
    });

You declare your function using var which will be done when the line is reached. So when you call it in your callback, the function has not been defined yet. To be able to use it, either move it before lineReader.on('line', function(){}) or (better) define it like that:

function dataCollector(folder_names, data) {
  /* Your function */
}

Doing it this way, your function is declared before your script is executed, and thus it exists when you reach your callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM