简体   繁体   English

Nodejs readline 回调

[英]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我得到: dataCollector is not a function

You're shadowing the dataCollector identifier here:您在此处隐藏dataCollector标识符:

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.这将dataCollector声明为回调的第二个参数,隐藏(隐藏)脚本顶层的标识符。

The line event doesn't document that it provides a second argument to its callback, so it should look like this: line事件没有记录它为其回调提供了第二个参数,因此它应该如下所示:

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:在您的情况下,您可能希望在close事件处理程序中执行console.log

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.您使用var声明您的函数,这将在到达该行时完成。 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:为了能够使用它,将它移动到lineReader.on('line', function(){})或(更好)像这样定义它:

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.这样做,你的函数在你的脚本执行之前被声明,因此当你到达你的回调时它存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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