Alexander Gonchiy
Alexander Gonchiy

Reputation: 947

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!"

Upvotes: 1

Views: 114

Answers (1)

Andrei Karpuszonak
Andrei Karpuszonak

Reputation: 9034

utils.js

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

usesUtils.js

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

Upvotes: 1

Related Questions