Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

javascript - Does require in node uses eval to run a code in another file

I was just trying to understand modules in node. I understood few things like node creates a module wrapper function around code placed in each file.

Let's say there are 2 files, a.js and b.js

In a.js, when i require b.js for first time, how will the module wrapper function which is present in b.js get's executed.

Does node do something like, get the whole content of b.js file as a string and then execute that from a.js using eval and then keep the result of this function call in cache.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

More or less.

Node.js loads script file contents and wraps with module wrapper:

Module.wrap = function(script) {
  return Module.wrapper[0] + script + Module.wrapper[1];
};

Module.wrapper = [
  '(function (exports, require, module, __filename, __dirname) { ',
  '
});'
];

Then module function is evaluated with vm.runInThisContext:

  var wrapper = Module.wrap(content);

  var compiledWrapper = vm.runInThisContext(wrapper, {
    filename: filename,
    lineOffset: 0,
    displayErrors: true
  });

vm module provides V8 execution context, and vm.runInThisContext evaluates the code similarly to indirect eval:

vm.runInThisContext() compiles code, runs it within the context of the current global and returns the result. Running code does not have access to local scope, but does have access to the current global object.

<...>

Because vm.runInThisContext() does not have access to the local scope, localVar is unchanged. In contrast, eval() does have access to the local scope, so the value localVar is changed. In this way vm.runInThisContext() is much like an indirect eval() call, e.g. (0,eval)('code').


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...