The description in the code comments is very clear, so there will be no more nonsense here, just give the code:
/*
* All script files in node are a module file, so 1.js is also a module file, and since the file is directly run through the node command in the command line window, the module file is defined in node For the main module of the application
* You can use the following method to detect whether the current module is the main module
* */
if(module===require.main){
console.log("The current module is the main module");
}
//Output result: The current module is the main 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 is referenced twice, the output of console.log(name) is only executed once.
/*require.resolve(str)
* In node, you can use this function to query the file name of a module file with a complete absolute path.
* */
var url=require.resolve("./2");
console.log(url);
//Output result:E:nodegys2.js
/*require.cache
* In node, this attribute 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 the delete keyword is used to delete a module object cached in the cache area, the code in the module will be re-run the next time the module is loaded. Usage 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.