Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

回调函数中的参数列表是规定好的么???(java 过来的 ,是不是我有什么思维定势)

$
0
0

1.自己写的测试中使用了 fs模块的readFile方法。想知道这个方法的回调为社么这么写? 为什么第一个参数是err,第二个参数是data. 在这个回调中竟然很神奇的拿到了数据

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});
console.log("程序执行完毕");

2.然后我就想看看 这个回调是怎么拿到err 和data 的数据的,找到了源码

fs.readFile = function(path, options, callback_) {
  var callback = maybeCallback(arguments[arguments.length - 1]);

  if (!options || typeof options === 'function') {
    options = { encoding: null, flag: 'r' };
  } else if (typeof options === 'string') {
    options = { encoding: options, flag: 'r' };
  } else if (typeof options !== 'object') {
    throwOptionsError(options);
  }

  var encoding = options.encoding;
  assertEncoding(encoding);

  var flag = options.flag || 'r';

  if (!nullCheck(path, callback))
    return;

  var context = new ReadFileContext(callback, encoding);
  var req = new FSReqWrap();
  req.context = context;
  req.oncomplete = readFileAfterOpen;

  binding.open(pathModule._makeLong(path),
               stringToFlags(flag),
               0o666,
               req);
};



function nullCheck(path, callback) {
  if (('' + path).indexOf('\u0000') !== -1) {
    var er = new Error('Path must be a string without null bytes.');
    er.code = 'ENOENT';
    if (typeof callback !== 'function')
      throw er;
    process.nextTick(callback, er);
    return false;
  }
  return true;
}


function ReadFileContext(callback, encoding) {
  this.fd = undefined;
  this.size = undefined;
  this.callback = callback;
  this.buffers = null;
  this.buffer = null;
  this.pos = 0;
  this.encoding = encoding;
  this.err = null;
}

可是源码里里面没有说啊 ,这到底是怎么回事? 谢谢


Viewing all articles
Browse latest Browse all 14821

Trending Articles