Search code examples
javascriptnode.jsv8

How can I globally add methods to JSON, Date or other 'native' objects in nodejs?


I know that doing that is bad, but still.

I have a module with utilities I often use. Inside it, if I declare, for example,

JSON.foo = function(){return "Hi!";};

then the JSON.foo method will be available, but only inside the module.


How can I make it available from outside the module, where I require it?

i.e.

var utils = require("utils");
console.log(JSON.foo()); // "Hi!"

Solution

  • utils.js

    JSON.foo = function(){return "Hi!";};
    exports.JSON = JSON
    

    usesUtils.js

    var utils = require("./utils");
    console.log(JSON.foo()); // "Hi!"