Home >Web Front-end >JS Tutorial >Detailed explanation of Node global variable global module instance
This article mainly introduces the Node global variable global module. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Environment: Node v8.2.1; Npm v5.3.0; OS Windows10
In the browser we have the window object for mounting global variables, in Node we have The global object can be mounted, and many common attributes can be mounted to the global object, which itself also has many attributes.
1. API structure diagram
2. Some examples
The following are Examples of some APIs, a simple code implementation of some APIs
2.1 global
Global namespace, variables defined through global can be used anywhere, Similar to variables defined in the global scope on the browser side.
// foo.js global.foo = 'hello';
// bar.js require('./foo'); console.log(foo); //hello
Variables defined on global do not need to be output through exports in the module and can also be used in other modules.
2.2 __dirname
dirname is not actually a global variable. Direct calling in command line mode will prompt that dirname is undefined, but it can be used directly in the module. Return The directory where the current script is executed.
console.log(__dirname);
2.3__filename
Returns the name of the currently executing code file (including the absolute path to the file). Like dirname, filename is not a global variable, but can be used directly in the module.
console.log(__filename);
__filename returns the file name including the path.
Related recommendations:
In-depth understanding of the Global module in Nodejs
The above is the detailed content of Detailed explanation of Node global variable global module instance. For more information, please follow other related articles on the PHP Chinese website!