Node.js custom module

Node.js built multiple modules, you can use third-party modules, today learn how to use their own definition of module

 

Define two js files in the same directory

First: custom1.js

"use strict";

function hello() {

  console.log("Hello world!!");

}

// a self-defined function hello thrown to the outside

module.exports = hello;

 

Second: custom2.js

"use strict";

// throws module introduced above, attention here is the introduction of the above file name

let test = require("./custom1");

// use custom1 thrown hello function

test();

 

to sum up:

1. Node require the introduction of modules (whether or custom built)

2. Use the test file with content stored custom1.js module.exports thrown

3.module.exports thrown content can be anything (strings, functions, objects, etc.)

4. The introduction of custom modules when needed preceded by "./", or it may be an error, do not add "./" it will find the built-in module to module

5. introduced in the Node module built into more of a use. "" To use this module, in fact, we also can use this, just thrown when the object is to throw the contents of

For example, after using module.exports throw things we can do again custom1.js file:

module.exports = {"hello" : hello};

So that we can use in custom2.js file  test.hello ()  is used in the form hello method

 

Guess you like

Origin www.cnblogs.com/hros/p/10990338.html