J2V8 icon indicating copy to clipboard operation
J2V8 copied to clipboard

Replace built-in modules (such as fs and http)

Open BEllis opened this issue 6 years ago • 4 comments

Not sure how feasible this is, but I'd like to be able to replace the FS and HTTP modules with my own implementations such that I can get it to send/receive request and responses to my Java Servlet Container, and, make Java resources available as if they were on the file system (and/or sandbox the files visible to V8).

BEllis avatar Jul 02 '19 14:07 BEllis

If you don't want to modify the source code and struggle with compile your own version of j2v8, you can simply wrap the global require object to make sure the return value of require(someBuiltInModule) is what you want. To put it simply, invoke your own JavaScript function to do whatever you want to prepare every JavaScript runtime environments.

Wrapping/replacing functions/objects at JavaScript level is quite simple, for example:

/**
 * This function should be invoked (via `j2v8` API, of course) every time you initialize a new isolation
 */
async function __J2V8_INIT__() {
  const oldRequire = require
  global.require = (path) => {
    const mod = oldRequire(path)
    switch(path) {
      case 'fs': {
        // Replace functions as you wish
        const oldReadFile = mod.readFile
        mod.readFile = (...args) => {
          console.log(`Oops, someone wants to read ${args[0]}`)
          return oldReadFile(...args)
        }
        return mod
      }
      // Some other cases
      default: return mod
    }
  }
}

Edit: As for the virtual file system, I would like to suggest you to implement the feature in JavaScript or write a native addon to deal with .jar files for quicker I/O. (I can't find any existing .jar file parser on npmjs.com and github)

Luluno01 avatar Jul 05 '19 09:07 Luluno01

Thanks. I'll give that a go! Didn't know about the J2V8_INIT function.

BEllis avatar Jul 05 '19 11:07 BEllis

JSZip may work for parsing JAR files.

https://stuk.github.io/jszip/

BEllis avatar Jul 05 '19 12:07 BEllis

Please note that J2V8_INIT is some random function name that I took as an example. You may define your own environment-preparation/initialization function with any unique valid identifier. Most importantly, the initialization function will not be executed by itself. You need to manage to execute the function on your own.

Check my project for example, where I wrote a bunch of files for environment preparation and execute the entry file before Node.js runtime can execute other codes.

Luluno01 avatar Jul 06 '19 05:07 Luluno01