簡體   English   中英

Nodejs readline 回調

[英]Nodejs readline callback

我正在研究回調,但由於某種原因我無法正確理解......我想讀取一個文件,並將它的數據保存到一個全局變量中以供以后使用。

這是我到目前為止所擁有的:

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.

怎么了? 我得到: dataCollector is not a function

您在此處隱藏dataCollector標識符:

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

這將dataCollector聲明為回調的第二個參數,隱藏(隱藏)腳本頂層的標識符。

line事件沒有記錄它為其回調提供了第二個參數,因此它應該如下所示:

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

重新您對問題的擴展:

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

不,不應該。 為什么: 如何從異步調用返回響應?

在您的情況下,您可能希望在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
    });

您使用var聲明您的函數,這將在到達該行時完成。 因此,當您在回調中調用它時,該函數尚未定義。 為了能夠使用它,將它移動到lineReader.on('line', function(){})或(更好)像這樣定義它:

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

這樣做,你的函數在你的腳本執行之前被聲明,因此當你到達你的回調時它存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM