Home > Web Front-end > JS Tutorial > Node.js module system

Node.js module system

不言
Release: 2018-04-10 13:59:03
Original
1634 people have browsed it

The content shared with you in this article is about the Node.js module system, which has certain reference value. Friends in need can refer to it

What is a module? Modules are used to call functions between different node.js files. In other words, a js file can be a module.


1. Create module

main.js file:

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

hello.js file:

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

require () is used to obtain the module, and exports is the external interface object of the module. In the above example, require() obtains the interface of the hello module, returns the exports object and assigns it to the hello object. The .world() method serves as the exposed interface.

We can also use the entire object as the external interface.

For example:

//hello.js 
function Hello() { 
    var name; 
    this.setName = function(thyName) { 
        name = thyName; 
    }; 
    this.sayHello = function() { 
        console.log('Hello ' + name); 
    }; 
}; 
module.exports = Hello;//HELLO对象作为接口
Copy after login

Then get this interface in main.js:

//main.js 
var Hello = require('./hello'); 
hello = new Hello(); 
hello.setName('BYVoid'); 
hello.sayHello();
Copy after login

Related recommendations:

Initial exploration of nodeJS_node.js

Node.js module system example detailed explanation

The above is the detailed content of Node.js module system. 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