Home > Backend Development > PHP Tutorial > Detailed explanation of Node.js module system examples

Detailed explanation of Node.js module system examples

小云云
Release: 2023-03-22 17:36:02
Original
1594 people have browsed it

In order to allow Node files to call each other, Node.js provides a simple module system. Modules are the basic components of Node.js applications. There is a one-to-one correspondence between files and modules. So, a Node.js file is a module. This module can be json, js or a compiled C/C++ extension.

The following is a brief introduction to the module system.

Create module

The following code simply creates a module and names it main.js. Among them, ./hello means that the hello.js file in the current directory is introduced. The default suffix of Node.js is js, so there is no need to add .js.

var hello = require('./hello');hello.world();
Copy after login

Node.js provides two objects for use by modules, namely require and export. Export is the public interface of the module. require is used to obtain the interface of a module from the outside, that is, to obtain the export object of the module. . Next create the hello.js file.

exports.world = function() {
  console.log('Hello World');}
Copy after login

You can see that hello.js uses the export object as the interface for external access. In main.js, the module is loaded through require to directly access the member functions of the export object. To be more advanced, if we just want to encapsulate an object into a module, we can use the following method, taking hello.js as an example.

function Hello() {     var name;     
this.setName = function(thyName) 
{         name = thyName;     };     
this.sayHello = function() {         
console.log('Hello ' + name);     }; 
}; 
module.exports = Hello
Copy after login
main.js:
var Hello=require('./hello');hello=new Hello();hello.setName('BYVoid');
hello.sayHello();
Copy after login

Execute output in the console: HelloBYVoid

require file search strategy:


Related recommendations:

Detailed explanation of Node.js module loading

Learn Nodejs with me---Node.js module

Node.js module encapsulation and usage_node.js

The above is the detailed content of Detailed explanation of Node.js module system examples. For more information, please follow other related articles on the PHP Chinese website!

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