0

I have a promisified method I called readFilePromise, that resolves to a Buffer object from fs' readFile method. When I execute the following line

return readFilePromise(filePath).then(Buffer.prototype.toString.call);

I get the following error:

TypeError: undefined is not a function

However, when I execute the block:

return readFilePromise(filePath).then((data) => {
    return Buffer.prototype.toString.call(data);
});

I get no error and the code executes fine.

In my mind they should be the same. Am I missing something obvious?

node v6.10.1

Ray Wadkins
  • 876
  • 1
  • 7
  • 16

1 Answers1

1

Buffer.prototype.toString.call is just Function.prototype.call which calls this using first object as a context. In your first example this inside call call will be undefined.

You need to bind call to Buffer.prototype.toString like this Buffer.prototype.toString.call.bind(Buffer.prototype.toString).

return readFilePromise(filePath)
   .then(Buffer.prototype.toString.call.bind(Buffer.prototype.toString))
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98