How to troubleshoot the “is not a function” error in JavaScript
When writing JavaScript, some developers prefer not to use semicolons for a cleaner code. However, there are situations where we need to be careful, especially when using the require()
function in Node.js to load external modules and files.
In certain cases, you may encounter an error like this:
1 | TypeError: require(...) is not a function |
This error can be a bit confusing. Let’s go over how this error can occur.
For example, let’s say you require a library and then need to execute some code at the root level using an immediately-invoked async function:
1 | const fs = require('fs') |
Since there is no semicolon after require()
, and we start a line with a (
, JavaScript interprets it as an attempt to execute a function. In this case, it considers require('fs')
as the name of the function. Although it could work if the module export actually returned a function, it does not in this case. Hence, the ...is not a function
error occurs.
To resolve this issue, we need to add a semicolon somewhere. Here are two ways to fix it:
1 | const fs = require('fs') |
or
1 | const fs = require('fs'); |
It’s a small price to pay to avoid using semicolons everywhere.
Tip: top-level await is now available, and you can use it instead of this structure to prevent such errors.
tags: [“JavaScript”, “debugging”, “Node.js”, “semicolons”, “require”, “error troubleshooting”]