Node Standard JS Standard

A friend asked an interesting question, and I tried several things, but to no avail, is there any way to override the Node JS module?

For example, I want to override the readFile function to use the S3 bucket instead of the file system. I.e:

var fs = require('fs'); fs.readFile('my_text_file.txt', ...); 

Actually something like this works

 FileSystem.readFile = function () { // Connect to S3 and retrieve remote file } 

I tried the prototype, but it seems that they installed their own modules without the __proto__ object, they do not have the .constructor property, which means something to anyone.

I was thinking about using Nodes VM , but this is too strict, since I want the user to be able to install modules through npm and use them.

The closest I came to is to create a new module (since I can’t put a file named fs.js in my node_modules folder and require it, it just ignores it) and just sets the values ​​from fs to what I want, but this not quite right, I want the user to use require('fs') and use my custom function.

Is this possible without compiling my own version of Node JS?

+6
source share
1 answer

I feel obligated to categorically warn you about the abandonment of the basic functions. However, this will work:

main.js:

 var fs = require('fs'), oldReadFile = fs.readFile; fs.readFile = function (filename, options, callback) { console.log('hey!'); oldReadFile(filename, options, callback) }; var other = require('./other'); other.test(); 

other.js:

 var fs = require('fs'); exports.test = function () { fs.readFile('./main.js', {encoding: 'utf8'}, function (err, data) { console.log(err, data); }); }; 

You will need to wrap the user script with your own in order to first redefine what you want.

+11
source

Source: https://habr.com/ru/post/947153/


All Articles