javascript回调-处理读取文件与fs.readFile

javascript callbacks - handle reading a file with fs.readFile

本文关键字:fs readFile 文件 读取 回调 处理 javascript      更新时间:2023-09-26

对于一个项目,我正在使用net模块创建一个'迷你web框架'

我在处理这个回调时遇到了很多麻烦

var sendFile(path) {
  fs.readFile(path, config, this.handleRead.bind(this));
}

readFile定义为:

var handleRead = function(contentType, data, err) {
  if (err) {
    console.log(err);         //returns properly
  } else {
    console.log(data);        //returns properly
    console.log(contentType)  //returning undefined
}

到目前为止,这段代码的工作原理是,我可以捕获错误,也可以正确地编写数据。

我的问题是:我如何通过回调发送contentType ?

I've try -

var sendFile(path) {
  var contentType = ContentType['the path type']
  fs.readFile(path, config, this.handleRead(contentType).bind(this));
}

但是这会导致data和err未定义。

我对js很陌生,我仍然对如何使用回调感到困惑。任何输入是感激的!

.bind()让您做的不仅仅是设置"上下文"(函数的this值)。你也可以在函数中"绑定"参数。

试题:

function sendFile(path) {
  var contentType = ContentType['the path type']
  fs.readFile(path, config, this.handleRead.bind(this, contentType));
}

这将传递一个回调,其上下文设置为this,其第一个参数设置为contentType。只要这个回调是用data(也可能是err)调用的,那么一切都会正常工作。