简体   繁体   中英

non-blocking require in node.js

Is there a way to use require (or something else which is equivalent) on a server, at runtime (serve-time), without blocking the whole thing?

I'm trying to add functions defined by the user, after which he can use them in a language I'm implementing.

So, for example:

toaprse.mylanguage

#bind somefunctions.js
x = somefunctions.func1();

I could do a simple require('somefunction'); but I don't want to block node, which I understand is the case.

I just want to pass functions to my framework, it doesn't have to be require but it seems natural.

This is how require is implemented:

> console.log(require.extensions['.js'].toString())
function (module, filename) {
  var content = NativeModule.require('fs').readFileSync(filename, 'utf8');
  module._compile(stripBOM(content), filename);
}

You can do the same thing in your app. I guess something like this would work:

var fs = require('fs')

require.async = function(filename, callback) {
  fs.readFile(filename, 'utf8', function(err, content) {
    if (err) return callback(err)
    module._compile(content, filename)

    // this require call won't block anything because of caching
    callback(null, require(filename))
  })
}

require.async('./test.js', function(err, module) {
  console.log(module)
})

Take a look at Promises pattern. Using Promises, you can delegate execution of an asynchronous operation to a method which will call you back in case of errors or after successful execution of given operation.

Here is some node modules implementing this patterns:

It works, I Promise ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM