Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
The “is not a function” error is one of the most common JavaScript errors. Let’s explore when it happens and how to fix it.
The semicolon issue
If you write JavaScript without semicolons, you might encounter this error:
TypeError: require(...) is not a function
This happens when JavaScript misinterprets your code. Consider this example:
const fs = require('fs')
(async () => {
//...
})()
JavaScript doesn’t see a semicolon after require(), and we start a line with a (. JS thinks we’re trying to call a function, treating require('fs') as the function name.
The fix
Add a semicolon. Either at the end of the previous line:
const fs = require('fs');
(async () => {
//...
})()
Or at the beginning of the IIFE:
const fs = require('fs')
;(async () => {
//...
})()
Tip: Top-level await is now a thing in modern JavaScript, so you can use
awaitdirectly at the top level instead of wrapping it in an IIFE.
The cb.apply is not a function error
Another variant is cb.apply is not a function, which can occur with certain npm packages after a Node.js version upgrade.
This typically happens with packages like graceful-fs when running older tools. If you encounter this:
- Check if the tool you’re using has an update
- Consider using a Node version manager to switch to a compatible Node.js version
- As a last resort, you can patch the problematic file by commenting out the offending code
For example, in graceful-fs/polyfills.js, you might need to comment out:
// fs.stat = statFix(fs.stat)
// fs.fstat = statFix(fs.fstat)
// fs.lstat = statFix(fs.lstat)
General causes
The “is not a function” error generally occurs when:
- You’re trying to call something that isn’t a function
- A variable you expected to be a function is actually
undefinedor another type - You forgot to import a function
- Semicolon-less code is being misinterpreted