At the beginning

The module function “require” is commonly introduced in Nodejs code. Few people actually understand why “require” is used and how Nodejs works in general.

Remember “arguments”, arguments can be taken directly to the arguments passed to the calling function.

(function() {
  console.log(arguments)} / / [1, 2, 3]) (1.2.3)
Copy the code

Nodejs can print arguments directly. Run a file with Node:

// index.js
// nodeindex.js runs
console.log(arguments)
/ / output
/ / {' 0 ': {},
// '1':{ [Function: require]
/ / '2' :
// Module {
// id: '.',
// exports: {},
// parent: null,
// filename: 'D:\\Personal\\Desktop\\a
// loaded: false,
// children: [],
// paths:
// [ 'D:\\Personal\\Desktop\\abc\\nod
// 'D:\\Personal\\Desktop\\node_mod
// 'D:\\Personal\\node_modules',
// 'D:\\node_modules' ] },
// '3': 'D:\\Personal\\Desktop\\abc\\inde
// '4': 'D:\\Personal\\Desktop\\abc' }
Copy the code

You can see arguments has five arguments. The five parameters are exports, require, module, __filename, __dirname

The source code parsing

In the loader.js file of the Nodejs source code, you can see these lines of JS code

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

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

/ /...
Module.prototype._compile = function(content, filename) {
 content = internalModule.stripShebang(content);
  // create wrapper function
 var wrapper = Module.wrap(content);
/ /...
Copy the code

The general logic is:

Add ‘(function (exports, require, module, __filename, __dirname) {‘ to the header of the contents of the execution file.

Add ‘\n}) to the end of the executable file content; ‘

The next step in parsing is to convert the string into code (functions) to be called.

note

exports require module __filename __dirname