Node. JS Module System Examples

Source: Internet
Author: User
To allow node files to be called each other, node. JS provides a simple modular system. Modules are a basic part of the node. JS application, and the files and modules are one by one corresponding, so, a node. js file is a module that can be a JSON, JS, or a compiled c/s extension.

The following is a brief introduction to the module system.

Create a module

The following code simply creates a module named Main.js. Where./hello means that the Hello.js file is introduced in the current directory, and node. JS has the default suffix named JS, so you don't need to add. js.

var hello = require ('./hello '); Hello.world ();

node. JS provides two objects for the module to use, respectively, require and export,export are the public interfaces of the module, require is used to obtain an interface for a module externally, that is, to get the export object of the module. The Hello.js file is created below.

Exports.world = function () {  console.log (' Hello World ');}

As you can see, hello.js accesses the world as an externally accessed interface through the Export object, and then main.js the module by require to directly access the member functions of the Export object. More advanced, we just want to encapsulate an object in the module, we can use the following way, take 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
Main.js:var Hello=require ('./hello '); hello=new Hello (); Hello.setname (' byvoid '); Hello.sayhello ();

Perform output on console: hellobyvoid

Require file Lookup policy:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.