Tweaking a Node.js Core Module

Updated: November 18, 2021 By: Napoleon Post a comment

The example below shows you how to change the behavior of a Node.js core module by modifying or extending it. What we are going to do should not appear in serious products but might be somehow helpful for learning and testing purposes.

In this example, we will make some changes to fs/promises.

const fsPromises = require("fs/promises");

// Mutating an existing functionality
fsPromises.readFile = (fakePath) => {
  return "This is the fake data";
};

// Extending the module
fsPromises.sayHello = () => {
  console.log('Hello there!')
}

const run = async () => {
  fsPromises.sayHello();
  
  const data = await fsPromises.readFile("a-mock-file");
  console.log(data);
};

run();

Run the code and you should get this output in your console:

Hello there!
This is the fake data

Further reading:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles