Reputation: 15903
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
Upvotes: 2
Views: 2765
Reputation: 2442
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(){}
Upvotes: 6
Reputation: 54999
Here's an example of how to do it:
https://github.com/mikeal/node-utils/blob/master/file/lib/main.js
Upvotes: 1
Reputation: 25436
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.
Upvotes: 1