Simple nodejs callback example with fs.readFile

后端 未结 3 1782
予麋鹿
予麋鹿 2021-02-11 05:55

I\'m trying to learn async programming and was struggling with lesson 4 of nodeschool.io with the implementation of an async io with callbacks.

Basically, I\'m trying to

3条回答
  •  不要未来只要你来
    2021-02-11 06:30

    Trying to treat errors as well. Not sure, if it is better to propagate the error in the last callback. I think the functionality is quite basic, but anyway I am propagating errors.

    I would also say is more correct to delegate the split in the last callback rather than passing it through an argument or similar.

    var fs = require('fs');
    var myfile = process.argv[2];
    
    
    
    function solution(file, callback){
    fs.readFile(file, "utf-8", function (err, data) {
        if (err) callback(err);
        callback(null, data)
    });
    }
    
    function mycallback(err,data){
      if (err) callback(err) console.error(err);
      return data.split('\n').length-1);
    }
    
    solution(myfile,mycallback)
    

提交回复
热议问题