Reputation: 7078
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.
Upvotes: 2
Views: 1389
Reputation: 12265
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)
})
Upvotes: 4
Reputation: 3127
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 ;)
Upvotes: 2