While loading CommonJS modules, we use require statement, which is synchronous.
But doesn't loading modules involve reading them off the disk and interpreting them. So in a setup where we are advocating non blocking I/O how come require is synchronous ?
Update:
I have seen and used requireJS in the client and can appreciate its asynchronous nature. What I would like to know is that why doing something of this sort in the server is not widespread (I know requireJS can be used in Node but that is not the point).
Also I would like to know if requiring a module inline in my code makes my code blocking and if this is a bad practice and should be avoided.
requireing modules is generally something you do at the beginning of your program. If you don't do it at the beginning of your program, the results are cached anyways. Starting a program like this:
var fs = require('fs');
var http = require('http');
var oranges = require('oranges');
// Do stuff
Would work the same as starting one like this:
require('async', function(err, async) {
async.map(['fs', 'http', 'oranges'], function(err, modules) {
var fs = modules[0], http = modules[1], oranges = modules[2];
// Do stuff
});
});
The difference is that one of them is needlessly complicated. Yes, there could be some kind of syntactic sugar implemented, but it still wouldn't have any benefit, except in maybe some tiny edge cases.