在 node.js 中使用一个简单的模块

什么是 node.js 模块( 链接到文章 ):

模块将相关代码封装到单个代码单元中。创建模块时,可以将其解释为将所有相关功能移动到文件中。

现在让我们看一个例子。想象一下所有文件都在同一目录中:

档案:printer.js

"use strict";

exports.printHelloWorld = function (){
    console.log("Hello World!!!");
}

使用模块的另一种方式:

文件 animals.js

"use strict";

module.exports = {
    lion: function() {
        console.log("ROAARR!!!");
    }

};

档案:app.js

通过转到你的目录并键入:node app.js 来运行此文件

"use strict";

//require('./path/to/module.js') node which module to load
var printer = require('./printer');
var animals = require('./animals');

printer.printHelloWorld(); //prints "Hello World!!!"
animals.lion(); //prints "ROAARR!!!"