7

I want to add or override some standard methods of Object, Function and Array (e.g., like suggested in this answer) in node.js application. How should I do all the "patches" in just one module so that it affects all my other modules?

Will it be enough if I do it in a module that is just require'd or it won't work because the two modules have different global namespaces so they have different Object?... Or should I run some initialisation function after require that makes all these "patches" working in this module too?

Community
  • 1
  • 1
esp
  • 7,314
  • 6
  • 49
  • 79

2 Answers2

13
//require the util.js file 
require('./util.js');

var a = [];
a.doSomething();

in your "util.js" file:

//in your util.js file you don't have to write a module, just write your code...
Array.prototype.doSomething = function(){console.log("doSomething")};
user934801
  • 1,119
  • 1
  • 12
  • 30
7

Each file loaded shares the same primordial objects like Object, Array, etc, unless run in a different vm Context, so requiring the file once in your initialization will make the changes everywhere.

ckknight
  • 5,953
  • 4
  • 26
  • 23
  • Do you mean that it's even enough to require this module with "patches" once, only in my main module, and I don't need to require it in every module I want to have Object&co "patched"? – esp Jan 15 '13 at 00:40
  • 1
    Yes, it's enough to require it just once. All modules in node share the same global scope. They have a different *module* scope, but the same global scope. So they have the same `Object`, `Function`, `Array`, etc. – Nathan Wall Jan 15 '13 at 01:24
  • 1
    It works for Function.prototype and Array.prototype, but when I try to do it with Object.prototype it throws TypeError: TypeError: Property description must be an object: undefined at Function.defineProperty (native) at Object. (/opt/nginx/html/dev.stockscompare/node_modules/express/lib/express.js:53:10) – esp Jan 15 '13 at 16:41