I've been trying to add some convenience functions to Node's file system module (mainly because it lacks some mon sense things), but every time I begin fs.prototype.myfunc =
in the repl, Node plains 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
I've been trying to add some convenience functions to Node's file system module (mainly because it lacks some mon sense things), but every time I begin fs.prototype.myfunc =
in the repl, Node plains 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
Share
Improve this question
edited Dec 28, 2011 at 22:14
Tom van der Woerdt
30k7 gold badges74 silver badges105 bronze badges
asked Jun 19, 2011 at 10:54
Bailey ParkerBailey Parker
15.9k5 gold badges57 silver badges93 bronze badges
3 Answers
Reset to default 6What 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(){}
There might be a workaround, but node is sending you a message by not letting you monkey patch its modules. Doing require('fs-monkeypatch')
to get extra functions in require('fs')
is confusing. Just add your functions outside of the fs module.
Here's an example of how to do it:
https://github./mikeal/node-utils/blob/master/file/lib/main.js