最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prototyping Built-In Modules in NodeJS - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

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(){} 

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

发布评论

评论列表(0)

  1. 暂无评论