Home > Web Front-end > JS Tutorial > body text

Detailed explanation of Node global variable global module instance

小云云
Release: 2018-01-29 17:34:25
Original
1594 people have browsed it

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

Detailed explanation of Node global variable global module instance

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';
Copy after login


// bar.js
require('./foo');
console.log(foo);
//hello
Copy after login

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);
Copy after login

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);
Copy after login

__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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!