Should I avoid calling when responding to a request?

Is it a requiremodule blocking every single request? According to docs , the module is cached after the first require, but I would like to see if it will be an anti-pattern for dynamic requirewhen responding to a request.

+3
source share
3 answers

No, it will not be blocked on every request (if you require the same module every time), and this is not an anti-pattern.

If you load the same module for each request, any call requirewill return instantly (because the module will already be loaded, compiled and cached). If, however, many different modules may be required so that you do not get the benefits of caching, it might be better to perform an asynchronous request.

But something like this?

function handler(req, res) { require('fs').readFile(…); }

No big deal. It is just a matter of style.

+3
source

I am often told that blocking of any type is a no-no in node.js, and that asynchrony is one of its main imperatives. You can try the following.

A quote from a non-blocking response is required in node.js


Here's how it 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 in your application. I think something like this will 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)
})
+1
source

It is not slow or fast. require synchronous operation. This means that it blocks the entire server at runtime. If you have 100,000 connections, everyone will wait for 100,000.

Never use the required inner loop; this is bad practice.

So the answer to your original question is YES.

0
source

All Articles