简体   繁体   English

使用fs.readFile的简单nodejs回调示例

[英]Simple nodejs callback example with fs.readFile

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. 我正在尝试学习异步编程,并且正在努力学习nodeschool.io的第4课,并实现了带回调的异步io。

Basically, I'm trying to use fs.readFile to count the number of newlines within a file using a callback. 基本上,我正在尝试使用fs.readFile来计算使用回调的文件中的换行符数。

Here's my code: 这是我的代码:

var fs = require('fs');
var pathToFile = process.argv[2];

function counter(callback) {
    var buffer = fs.readFile(pathToFile, function (err, data) {
    var bufferString = buffer.toString();
    var bufferStringSplit = bufferString.split('\n');
  });
  callback();
}

function logMyNumber() {
  console.log(bufferStringSplit.length-1);
}

counter(logMyNumber);

I understand that callbacks are executed once the line of code is finished executing, so shouldn't the 我知道一旦代码行完成执行就会执行回调,所以不应该执行

var bufferString = buffer.toString();
var bufferStringSplit = bufferString.split('\n');

be called after fs.readFile() finishes reading the file from disk? 在fs.readFile()完成从磁盘读取文件后调用?

Then finally the callback() calls logMyNumber, which should just output the number of lines the file has. 最后,callback()调用logMyNumber,它应该只输出文件所具有的行数。

You have several issues going on and I'll try to outline them all as best as possible 您有几个问题正在进行中,我将尝试尽可能地概述它们

Problem 1: Variable scope 问题1:可变范围

var fs = require('fs');
var pathToFile = process.argv[2];

function counter(callback) {
  var buffer = fs.readFile(pathToFile, function (err, data) { 
    // Both of the following variables are scoped to the callback of fs.readFile
    var bufferString = buffer.toString(); 
    var bufferStringSplit = bufferString.split('\n'); 
  });
  callback();
}

function logMyNumber() {
  // Because the variables are in a closure above, bufferStringSplit is null here
  console.log(bufferStringSplit.length-1);
}

counter(logMyNumber);

Solution: 解:

Declare the variables in the module's scope: 声明模块范围内的变量:

var fs = require('fs');
var pathToFile = process.argv[2];

// These can now be accessed from anywhere within the module
var bufferString, bufferStringSplit;

function counter(callback) {
  fs.readFile(pathToFile, function (err, data) {
    bufferString = data.toString(); 
    bufferStringSplit = bufferString.split('\n'); 
    callback();
  });
}

// bufferStringSplit should no longer return null here
function logMyNumber() {
  console.log(bufferStringSplit.length-1);
}

Problem 2: Callbacks 问题2:回调

function counter(callback) {
  fs.readFile(pathToFile, function (err, data) {
    bufferString = buffer.toString(); 
    bufferStringSplit = bufferString.split('\n'); 

    // Place the callback WITHIN the other callback, otherwise they run in parallel
    callback();
  });
}

Problem 3: fs.readFile API 问题3:fs.readFile API

fs.readFile doesn't return anything, so your buffer variable below is null fs.readFile不返回任何内容,因此下面的buffer变量为null

function counter(callback) {      
  var buffer = fs.readFile(pathToFile, function (err, data) {
    bufferString = buffer.toString(); 
    bufferStringSplit = bufferString.split('\n'); 
  });
  callback();
}

Solution: 解:

function counter(callback) {      
  fs.readFile(pathToFile, function (err, data) {
    // The data argument of the fs.readFile callback is the data buffer
    bufferString = data.toString(); 
    bufferStringSplit = bufferString.split('\n'); 
  });
  callback();
}

Finally, the code should look like: 最后,代码应如下所示:

var fs = require('fs');
var pathToFile = process.argv[2];

var bufferString, bufferStringSplit;

function counter(callback) {
  fs.readFile(pathToFile, function (err, data) {
    bufferString = data.toString(); 
    bufferStringSplit = bufferString.split('\n'); 
    callback();
  });
}

function logMyNumber() {
  console.log(bufferStringSplit.length-1);
}

counter(logMyNumber);

Same problem for me. 对我来说同样的问题。 This is my solution. 这是我的解决方案。

var fs = require('fs');
var file = process.argv[2];

function count(pFile, callback) {
  fs.readFile(pFile, "utf8", function(err, data){
     callback(data.split("\n").length-1);
  });
}

count(file, console.log);

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)

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

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