The code comments have been described very clearly, so I won’t talk much nonsense here, just present the code:
The code copy is as follows:
/*In node, the module can be loaded using the require() function.
* The require function uses a parameter. The parameter value can be the file name of the module with a full path or the module name. When using the module provided in node, you only need to specify the module name in the require function.
* */
//Create a page 2.js; the code is as follows
var name="Dr. Sisi";
exports.name=name;
//Create a page 1.js; the code is as follows
var two=require("./2.js");
console.log(two.name);
//Output result: Dr. Sisi
/*
* All script files in node are a module file, so 1.js is also a module file. Since the file is run directly through the node command in the command line window, the module file is defined as the main module of the application in node.
* You can use the following method to detect whether the current module is the main module
* */
if(module===require.main){
console.log("Main module at the current module");
}
//Output result: The main module is currently in the module
//2.js code
var name="Dr. Sisi";
console.log(name);
exports.name=name;
//1.js code:
var two=require("./2.js");
var two=require("./2.js");
//Although it was referenced twice, it was only executed 1 time to output console.log(name).
/*require.resolve(str)
* In node, this function can be used to query the file name with a complete absolute path of a module file.
* */
var url=require.resolve("./2");
console.log(url);
//Output result: E:/node/gys/2.js
/*require.cache
* In node, this property represents the cache area of all loaded modules.
* */
var two=require("./2.js");
var cache=require.cache;
console.log(cache);
/*Output result:
* { 'E://node//gys//1.js':
{ id: '.',
exports: {},
parent: null,
filename: 'E://node//gys//1.js',
loaded: false,
children: [ [Object] ],
paths:
[ 'E://node//gys//node_modules',
'E://node//node_modules',
'E://node_modules' ] },
'E://node//gys//2.js':
{ id: 'E://node//gys//2.js',
exports: { name: 'Dr. Sisi' },
Parent:
{ id: '.',
exports: {},
parent: null,
filename: 'E://node//gys//1.js',
loaded: false,
children: [Object],
paths: [Object] },
filename: 'E://node//gys//2.js',
loaded: true,
children: [],
paths:
[ 'E://node//gys//node_modules',
'E://node//node_modules',
'E://node_modules' ] } }
* */
//2.js code
var name="Dr. Sisi";
console.log(name);
//1.js code
//When you use the delete keyword to delete a module object cached in the cache, the next time the module is loaded, the code in the module will be re-run. Use the code:
var two=require("./2.js");
var two1=require("./2.js");
console.log("before deletion")
delete require.cache[require.resolve("./2.js")];
console.log("After deletion");
var two2=require("./2.js");
/*
* Output result:
* Dr. Sisi
* Before deletion
* After deletion
* Dr. Sisi
* */
Do you guys know how to use require in node.js? If you have any questions, please leave a message.