简体   繁体   English

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

[英]javascript callbacks - handle reading a file with fs.readFile

For a project, I am using the net module to create a 'mini web framework' 对于一个项目,我正在使用net模块来创建“迷你Web框架”

I'm having a lot of trouble dealing with this one callback 我在处理此回调时遇到很多麻烦

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

where readFile is defined as: 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
}

So far this code works in the sense that I can catch errors and also write the data properly. 到目前为止,此代码在某种意义上可以正常工作,因为我可以捕获错误并正确写入数据。

My question is : how do I send the contentType through the call back? 我的问题是:如何通过回叫发送contentType?

I've tried - 我试过了 -

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

But then this causes data and err to be undefined. 但这会导致数据和错误未定义。

I'm quite new to js and am still confused about how to work with callbacks. 我对JS还是很陌生,但对如何使用回调仍然感到困惑。 Any input is appreciated! 任何输入表示赞赏!

.bind() lets you do more than just set the "context" ( this value of a function). .bind()可以设置“上下文”(函数的this.bind() ,还可以做更多的事情。 You can also "bind" arguments in the function. 您也可以在函数中“绑定”参数。

Try: 尝试:

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

This will pass a callback with its context set to whatever this is and its 1st parameter set to contentType . 这将传递一个回调,其上下文设置为this ,其第一个参数设置为contentType As long as this callback is called with data (and possibly err ), then everything will work. 只要使用data (可能还有err )调用此回调,那么一切都会起作用。

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

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