Override function of a Node.js module
Override function of a Node.js module – There could be scenarios where you would like to improve the functionalities of existing modules by overriding them.
In this tutorial, we shall learn to override a function of a Node.js module in a CommonJS project. We shall also cover safer alternatives, because replacing a function on a module object can affect other code running in the same Node.js process.
In Node.js, overriding usually means replacing an exported function with another function that has the same name. For example, you may replace a method to add logging, change a small behavior in an internal script, or create a mock while testing. Use this pattern carefully when the module is shared across the application.
Steps to Override Function of a Module in Node.js
To override an existing function of a Node.js module, following is a step by step guide.
Step 1: Include the module.
The first step to override a function in a module is to include the module itself using require function.
var newMod = require('<module_name>');
We have retrieved the module to a variable.
This tutorial uses CommonJS syntax. In CommonJS, require() returns the module exports object, and you can assign a new function to one of its properties. In ES modules, imported bindings are not meant to be reassigned in the same way, so a wrapper function is usually the better option.
Step 2: Delete function from the module variable.
Using variable to the module, newMod , delete the function from it using following syntax.
delete newMod['<function_name>'];
Please remember that the changes would be only to the module variable, newMod, but not to the original module itself.
In many cases, deleting the function first is not required. Assigning a new function to the same property name is enough to replace the old function. Deleting first is useful only when you intentionally want to remove the property before assigning it again.
Step 3: Add function, with same name, to the module variable.
Using variable to the module, newMod , add the function with the same name, that we deleted in the previous step, using following syntax.
newMod.<function_name> = function(function_parameters) {
// function body
};
Step 4: Re-export the module.
You have to re-export the module for the overriden functionalities to take effect.
module.exports = newMod;
Now, you may use the variable to the module, newMod , for calling the function, and the overridden functionality would be executed.
Example 1 – Override Function of a Node.js Module
In this example, we shall override readFile() function of Node fs module.
node-js-overriding-function-in-module.js
// include the module whose functions are to be overridden
var fs = require('fs');
// delete the function you would like to override
delete fs['readFile'];
// add new functional with the same name as deleted function
fs.readFile = function(str){
console.log("The functionality has been overridden.");
console.log(str);
}
// re-export the module for changes to take effect
module.exports = fs
// you may use the newly overriden function
fs.readFile("sample.txt");
Open a terminal or command prompt and run this script using node command as shown in the following.
Output
~/workspace/nodejs$ node node-js-overriding-function-in-module.js
Message from newly added function to the module
sample.txt
Overriding readFile() function may not be a great idea, but would suffice for demonstration.
Override a Node.js module function by direct assignment
The simplest way to override a CommonJS module function is to save a reference to the original function, then assign a new function to the same property. Saving the original function is useful when you want to add behavior before or after the original implementation instead of replacing it completely.
fs-readfile-override.js
const fs = require('fs');
const originalReadFile = fs.readFile;
fs.readFile = function (filePath, options, callback) {
console.log('Reading file:', filePath);
if (typeof options === 'function') {
callback = options;
options = undefined;
}
return originalReadFile.call(fs, filePath, options, callback);
};
fs.readFile('sample.txt', 'utf8', function (error, data) {
if (error) {
console.error(error.message);
return;
}
console.log(data);
});
In the above example, the custom readFile() function logs the file path and then calls the original fs.readFile(). The call() method keeps the original function context explicit.
Use a local wrapper instead of overriding a built-in Node.js module
For application code, a wrapper is often safer than changing the module object directly. A wrapper gives your project a custom function without changing how the original module behaves for other files.
file-reader.js
const fs = require('fs');
function readFileWithLog(filePath, options, callback) {
console.log('Reading file:', filePath);
return fs.readFile(filePath, options, callback);
}
module.exports = {
readFileWithLog
};
app.js
const { readFileWithLog } = require('./file-reader');
readFileWithLog('sample.txt', 'utf8', function (error, data) {
if (error) {
console.error(error.message);
return;
}
console.log(data);
});
This approach keeps the custom behavior visible. When another developer sees readFileWithLog(), they can understand that it is a project helper and not the original fs.readFile() function.
CommonJS module cache effect while overriding functions
CommonJS modules are cached after the first time they are loaded. If one file overrides a function on the exported module object, another file that receives the same cached object may also see the changed function. The original module file is not rewritten on disk, but the runtime object can be shared inside the same process.
The order of imports matters. If a file expects the overridden function, make sure the override file is loaded before that function is called.
// load-overrides.js
const fs = require('fs');
const originalExistsSync = fs.existsSync;
fs.existsSync = function (path) {
console.log('Checking path:', path);
return originalExistsSync(path);
};
module.exports = fs;
// app.js
require('./load-overrides');
const fs = require('fs');
console.log(fs.existsSync('sample.txt'));
This style can be useful in controlled scripts, but it can become difficult to track in larger projects. Keep overrides close to the application entry point if you use them.
Override a function from your own Node.js module
Overriding your own module is easier to reason about than overriding a built-in or third-party module. The following example replaces a function exported from a local module.
calculator.js
function add(a, b) {
return a + b;
}
module.exports = {
add
};
app.js
const calculator = require('./calculator');
calculator.add = function (a, b) {
console.log('Using overridden add function');
return Number(a) + Number(b);
};
console.log(calculator.add('10', '20'));
Output
Using overridden add function
30
ES module alternative for overriding behavior in Node.js
If your Node.js project uses ES module syntax, avoid trying to mutate imported module bindings. Instead, import the original function and export a new function from your own module.
math-helper.mjs
import { readFile } from 'node:fs/promises';
export async function readTextFile(filePath) {
console.log('Reading file:', filePath);
return readFile(filePath, 'utf8');
}
app.mjs
import { readTextFile } from './math-helper.mjs';
const data = await readTextFile('sample.txt');
console.log(data);
This gives you overridden behavior in practice, without changing the imported module namespace.
When overriding a Node.js module function is a bad idea
Overriding a module function changes expected behavior. Before using it in application code, check whether a wrapper, configuration option, middleware, dependency injection, or test mock would solve the same problem more clearly.
- Avoid overriding core module methods globally unless the code is a small internal script or a controlled test setup.
- Avoid overriding third-party package functions directly because package updates can change the function signature or internal behavior.
- Do not remove expected arguments from the replacement function if other code still calls it with the original signature.
- Do not hide side effects in a file that is imported far away from the application entry point.
- Prefer wrappers for long-term maintenance because they make the custom behavior explicit.
Checklist before overriding a function in a Node.js module
- Confirm whether the project uses CommonJS or ES modules.
- Check the original function signature and keep compatible arguments where possible.
- Save the original function if the override still needs to call it.
- Load the override before any code depends on the modified behavior.
- Use a wrapper module when the change should be local and predictable.
- Document why the override exists, especially for third-party or built-in modules.
FAQ on overriding functions of Node.js modules
Can I override a function of a built-in Node.js module?
Yes, in CommonJS you can replace a function on the object returned by require(). For example, you can assign a new function to fs.readFile. This changes the runtime object inside the current process, not the original Node.js source file.
Do I need to delete the old function before overriding it?
No. In most cases, direct assignment is enough. For example, moduleObject.methodName = function () { ... } replaces the old function reference. Deleting first is optional and is rarely needed.
Will overriding a module function affect other files in Node.js?
It can affect other files in the same process if they use the same cached CommonJS module object after the override has been applied. This is one reason why wrappers are safer for application code.
How can I call the original function from the overridden function?
Store the original function in a variable before replacing it. Then call that saved function from inside the override, usually with call() or apply() if the original function needs a specific context.
What is the safest alternative to overriding a Node.js module function?
The safest alternative is usually a wrapper or helper module. The wrapper imports the original module and exports your custom function separately, so other code can choose the custom behavior without changing the original module object.
Editorial QA checklist for this Node.js override tutorial
- The tutorial explains that the direct override pattern applies to CommonJS modules loaded with
require(). - The tutorial warns that overriding a cached module object can affect other files in the same Node.js process.
- The tutorial shows how to preserve and call the original function before replacing it.
- The tutorial includes a wrapper module pattern for safer application code.
- The tutorial avoids recommending global overrides as the default pattern for production projects.
- The tutorial keeps the original demonstration while adding clearer examples for local modules and ES module projects.
Conclusion
In this Node.js Tutorial – Override function of a Node.js module, we have learnt to override functions of a Node.js Module with example Node.js Programs.
Overriding a function is possible when the exported module object can be changed at runtime. Use it with care, especially with built-in and third-party modules. For maintainable Node.js code, a wrapper module or helper function is often easier to understand and safer to test.
TutorialKart.com