How sync is require()?

45 views
Skip to first unread message

Ingwie Phoenix

unread,
Nov 5, 2015, 4:39:12 PM11/5/15
to nod...@googlegroups.com
Hey folks.

While developing a function that lets me require() custom files, I took the original JS and jSON "loaders" as examples.

But what I saw within the JS version confused me: It didn’T return a thing!


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


So - is require() "really" sync? Or, is it actually async?

Kind regards, Ingwie!

Andrey

unread,
Nov 6, 2015, 1:21:49 AM11/6/15
to nodejs
It is sync, but you are not returning anything. Result of  _compile is in module.exports.

This is the code I use to require manually (in my case I didn't want it to be cached by module system):

function myRequire(filename) {
   var m = new module.constructor();
   m.paths = module.paths;
   var src = fs.readFileSync(filename).toString();
   m._compile(src, filename);
   return m.exports;
}

Reply all
Reply to author
Forward
0 new messages