在父函数之前调用Javascript回调

时间:2016-07-24 20:25:31

标签: javascript node.js callback

我正在使用Node和Commander编写一个简短的脚本。它将显示给定文件的最后几行。我一直在尝试使用Node中的异步文件读取,但是在设置回调时遇到了很大的麻烦。似乎回调中的代码在父函数之前执行。这甚至可能吗?

这是脚本:

303 See Other

这是令人困惑的(至少对我来说)部分,输出。简而言之,我一直在尝试设置,以便在文件读取完成时调用输出所需行的回调。

#!/usr/bin/env node

const readline = require('readline');
const fs = require('fs');
const program = require('commander');
const chalk = require('chalk');

var consoleArguments = process.argv;

var fileValue ='';
var linesArray = [];

var main = function() {

}

function readFile(fileValue, callback){
    fs.readFile(fileValue, function(err, data) {
        console.log("Hello from fs.readFile callback! \nReading file: " + fileValue);
        var i = 0;
        if(err) throw err;
        linesArray = data.toString().split("\n");
        console.log("Hello from fs.readFile callback! Have just read the contents of file.\nThere are " + linesArray.length + " lines in the file!");
        for(i = 0; i <= linesArray.length - 1; i++) {
            //console.log(i +": " + linesArray[i]);
        }
        console.log("Returned linesArray from fs.readFile callback!");
        return linesArray;
    });
    console.log("Type of callback: " + typeof(callback));
    if (typeof callback === "function") {
          // Call it, since we have confirmed it is callable​
          callback(linesArray);
          console.log("Called callback");
    }
}



program
    .version('0.0.1')
    .arguments('<file>')
    .usage('[options] <file>')
    .option('-n, --number <number>', 'Display the last number of lines')
    .option('-f, --follow', 'Follow the file and display the last 10 lines as new lines are appended')
    .action(function(file) {
      fileValue = file;
    })
    .parse(process.argv);

if(!program.args.length) {
    program.help();
} else {
    //console.log('Keywords: ' + program.args); 
    console.log("File: " + fileValue);

    if (program.number && program.follow) {
        console.log('  - follow');
        console.log('  - number');
        console.log('Number passed to number option: ' + program.number);

    } else {

      if (program.number) {
          console.log('  - number');
          console.log('Number passed to number option: ' + program.number);

          console.log(readFile(fileValue, function(linesArray){
                console.log("Hello from readFile callback! \nAbout to output file lines!");
                var i = 0;
                var count = linesArray.length;
                var totalString = "";

                console.log(count);     

                for (i = count - 11; i <= count - 1; i++) {
                    totalString += linesArray[i];
                    totalString += '\n';
                    console.log(linesArray[i]);
                }           

          }));
      }

      if (program.follow) {
        console.log('  - follow');
      }        
    }
}  

if (program.args === null) program.help();  

EDIT1:

File: Word_List.txt
  - number
Number passed to number option: 10
Type of callback: function
Hello from readFile callback! 
About to output file lines!
0
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
Called callback
undefined
Hello from fs.readFile callback! 
Reading file: Word_List.txt
Hello from fs.readFile callback! Have just read the contents of file.
There are 235887 lines in the file!
Returned linesArray from fs.readFile callback!

编辑2: 以下是 Edit1

的输出
function writeLines(linesArray){
    console.log("Hello from writeLines callback! \nAbout to output file lines!");
    var i = 0;
    var count = linesArray.length;
    var totalString = "";

    console.log(count);     

    for (i = count - 11; i <= count - 1; i++) {
        totalString += linesArray[i];
        totalString += '\n';
        console.log(linesArray[i]);
    }           
}

function readFile(fileValue, writeLines){
    fs.readFile(fileValue, function(err, data, writeLines) {
        console.log("Hello from fs.readFile callback! \nReading file: " + fileValue);
        var i = 0;
        if(err) throw err;
        linesArray = data.toString().split("\n");
        console.log("Hello from fs.readFile callback! Have just read the contents of file.\nThere are " + linesArray.length + " lines in the file!");
        for(i = 0; i <= linesArray.length - 1; i++) {
            //console.log(i +": " + linesArray[i]);
        }
        writeLines(linesArray);
    });
}

1 个答案:

答案 0 :(得分:1)

fs.readFile是异步方法,这意味着您将在准备就绪时读取该文件,因此可以处理其余代码,直到读取准备就绪,这就是在文件完成之前调用回调的方式正在阅读。

你必须选择:

  1. 将回调函数放在最后的fs.readFile回调中。
  2. 你可以使用fs.readFileSync同步运行代码,这样只有在你读完文件后才会调用回调方法。
  3. 我认为第一个选项更好,因为这就是Node.js的工作方式。