mir-aclewhip mir-aclewhip - 2 months ago 15
Javascript Question

javascript callbacks - handle reading a file with fs.readFile

For a project, I am using the net module to create a 'mini web framework'

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:

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?

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. Any input is appreciated!

Answer

.bind() lets you do more than just set the "context" (this value of a function). 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. As long as this callback is called with data (and possibly err), then everything will work.