/

How to Resolve a \"cb.apply is not a function\" Error in Gitbook

How to Resolve a “cb.apply is not a function” Error in Gitbook

I regularly use Gitbook, a Node.js software that converts a set of markdown files into an ebook. Recently, while trying to generate a PDF using the command gitbook pdf ., I encountered a strange error:

1
2
3
4
5
6
7
➜ ebook git:(master) ✗ gitbook pdf .
/usr/local/lib/node\_modules/gitbook-cli/node\_modules/npm/node\_modules/graceful-fs/polyfills.js:287
if (cb) cb.apply(this, arguments)
^

TypeError: cb.apply is not a function
at /usr/local/lib/node\_modules/gitbook-cli/node\_modules/npm/node\_modules/graceful-fs/polyfills.js:287:18

The error message “cb.apply is not a function” left me wondering about its meaning and why it occurred at that moment. I hadn’t recently updated the gitbook package, but I realized that I had updated my Node.js version. This raised the suspicion that the Node.js version could be the cause.

Upon investigation, I discovered that the error originated from the /usr/local/lib/node_modules/gitbook-cli/node_modules/npm/node_modules/graceful-fs/polyfills.js file. This file is part of the graceful-js npm package, which is installed over 33 million times per week. It aims to improve the built-in Node.js fs module.

One of the improvements made by this package seemed to conflict with my workflow. However, I did not have much time to investigate the exact reason why my Node.js version caused this problem with Gitbook and graceful-js.

To fix the issue quickly, I decided to modify the /usr/local/lib/node_modules/gitbook-cli/node_modules/npm/node_modules/graceful-fs/polyfills.js file directly.

Here is the problematic function in the file:

1
2
3
4
5
6
7
8
9
10
11
function statFix (orig) {
if (!orig) return orig
return function (target, cb) {
return orig.call(fs, target, function (er, stats) {
if (!stats) return cb.apply(this, arguments)
if (stats.uid < 0) stats.uid += 0x100000000
if (stats.gid < 0) stats.gid += 0x100000000
if (cb) cb.apply(this, arguments)
})
}
}

This function seems to be addressing an issue in older versions of Node.js, which shouldn’t be relevant to my situation.

I noticed that this function is used in lines 62-64 of the same file:

1
2
3
fs.stat = statFix(fs.stat)
fs.fstat = statFix(fs.fstat)
fs.lstat = statFix(fs.lstat)

To temporarily bypass this problematic code, I commented out those lines:

1
2
3
// fs.stat = statFix(fs.stat)
// fs.fstat = statFix(fs.fstat)
// fs.lstat = statFix(fs.lstat)

After making this change, the gitbook command worked fine, and I successfully generated the PDF I needed.

tags: [“Gitbook”, “Node.js”, “error resolution”, “PDF generation”]