Callback argument must be a function
Production Risk
Low — caught immediately; switch to promise APIs to avoid callback type issues.
Thrown when a Node.js API that requires a callback function receives a non-function value. Many Node.js core APIs use callback-style async patterns where the last argument must be a function.
- 1Passing undefined as the callback argument (e.g. missing argument)
- 2Passing an object or string where a callback function is expected
- 3Accidentally omitting the callback in a function call
Triggered when a core API validates its callback argument and finds it is not a function.
const fs = require('fs');
fs.readFile('/tmp/data.txt', 'utf8', 'not-a-function'); // throwsexpected output
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received type string ('not-a-function')Fix 1
Pass a function as the callback argument
WHEN Always — check the API signature
const fs = require('fs');
fs.readFile('/tmp/data.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});Why this works
Providing a proper function satisfies the callback type check.
Fix 2
Use the promise-based API to avoid callbacks
WHEN When you prefer async/await
const { readFile } = require('fs/promises');
const data = await readFile('/tmp/data.txt', 'utf8');Why this works
The promise API does not require a callback argument, eliminating this class of error.
const fs = require('fs');
fs.readFile('/tmp/data.txt', 'utf8', 'not-a-function'); // throws // this triggers ERR_INVALID_CALLBACKtry {
// operation that may throw ERR_INVALID_CALLBACK
riskyOperation()
} catch (err) {
if (err.code === 'ERR_INVALID_CALLBACK') {
console.error('ERR_INVALID_CALLBACK:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_invalid_callback(...args) {
// validate args here
return performOperation(...args)
}✕ Pass non-function values as callbacks to async Node.js APIs
The callback is invoked asynchronously; a non-function value causes an immediate type error.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev