简体   繁体   English

node.js中的非阻塞需求

[英]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? 有没有一种方法可以在运行时(服务时间)在服务器上使用require (或其他等效的东西)而不会阻塞整个事情?

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 toaprse.mylanguage

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

I could do a simple require('somefunction'); 我可以做一个简单的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. 我只是想通过函数到我的框架,它并没有被require ,但它似乎很自然。

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. 看一下Promises模式。 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. 使用Promises,您可以将异步操作的执行委派给某个方法,该方法将在发生错误或成功执行给定操作后回调您。

Here is some node modules implementing this patterns: 以下是一些实现此模式的节点模块:

It works, I Promise ;) 它有效,我保证;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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