Search code examples
javascriptnode.jsprototype-programming

Prototyping Built-In Modules in NodeJS


I've been trying to add some convenience functions to Node's file system module (mainly because it lacks some common sense things), but every time I begin fs.prototype.myfunc = in the repl, Node complains that I am trying to set a property of an undefined variable. Is it really true that you cannot access Node's built-in module prototypes from the outside? If so, does anyone know a feasible workaround to extend Node's built-in modules?

Just to note: I did require fs before trying to prototype it!

var fs = require('fs');
fs.prototype.myfunc = function() {}; //TypeError thrown here

Solution

  • What you get back in response to a require('') depends upon the particular module. Some modules do this:

    module.exports = function() {}
    

    in that case, the value returned would be function and so would have a prototype you could attach things to.

    Other modules just set values on the already existing exports.module object. E.g:

    module.exports.someFunc = function(){}
    

    where module.exports is essentially just:

    module.exports = {}
    

    In the case of the fs module they do the latter:

    var fs = exports;
    
    ....
    
    fs.readFileSync = function(path, encoding) {
    

    So you get the error you do since the object returned isn't a function. You'd get the same error if you did this:

    var x = {};
    
    x.prototype.myfunc = function(){}
    

    Note you can just do:

    var fs = require('fs');
    
    fs.myFunc = function(){}