Modifying Other Modules
Learn how to modify bindings of modules.
We'll cover the following...
We saw that entities imported through ES modules are read-only live bindings, and therefore we cannot reassign them from an external module.
There’s a caveat, though. It’s true that we can’t change the bindings of the default export or named exports of an existing module from another module, but, if one of these bindings is an object, we can still mutate the object itself by reassigning some of the object properties.
This caveat can give us enough freedom to alter the behavior of other modules. To demonstrate this idea, let’s write a module that can alter the behavior of the core fs
module so that it prevents the module from accessing the filesystem and returns mocked data instead. This kind of module is something that could be useful while writing tests for a component that relies on the filesystem.
// mock-read-file.mjsimport fs from 'fs' // (1)const originalReadFile = fs.readFile // (2)let mockedResponse = nullfunction mockedReadFile (path, cb) { // (3)setImmediate(() => {cb(null, mockedResponse)})}export function mockEnable (respondWith) { // (4)mockedResponse = respondWithfs.readFile = mockedReadFile}export function mockDisable () { // (5)fs.readFile = originalReadFile}
Let’s review the preceding code:
The first thing ...