Friend has asked an interesting question and I've tried a few things but to no avail, is there any way to override a Node JS module?
For instance, I want to override the readFile function to use an S3 bucket instead of the filesystem. I.E:
var fs = require('fs');
fs.readFile('my_text_file.txt', ...);
Actually runs something like this
FileSystem.readFile = function () {
// Connect to S3 and retrieve remote file
}
I've tried the prototype but it seems they've set up native modules without the __proto__
object, they don't have a .constructor
property that means anything to anyone.
I've thought about using Nodes VM but this is too strict as I want the user to be able to install modules via npm
and use them.
The closest I've actually come is creating a new module (since I can't put a file named fs.js
in my node_modules
folder and require it; it just gets ignored) and just hard-setting the values of fs
to what I want but this isn't quite right, I want the user to be using require('fs')
and use my custom function.
Is this at all possible without compiling my own version of Node JS?
FileSystem
and then use that as a prototype for your custom object ("subclass" it). MyFS={FileSystem.call(this);};MyFs.prototype=new FileSystem(); Or use something like goog.base and goog.inherit to create a subclass that can call it's "parent" functions and deals with parameters passed to the constructor: docs.closure-library.googlecode.com/git/… Note that badse usesarguments.callee.caller
wich doesn't work in ecma 5 strict so you have to re write that. – HMR Jun 13 '13 at 0:41FileSystem
up for illustrative purposes, the modules don't have a__proto__
object and thus no constructor. The closest I've gotten is to directly set properties on the object and including another script but I want torequire('fs')
and it have my custom functionality – Dave Mackintosh Jun 13 '13 at 9:35