我试图实现的是创建一个包含多个功能的模块。

module.js:

module.exports = function(firstParam) { console.log("You did it"); },
module.exports = function(secondParam) { console.log("Yes you did it"); }, 
// This may contain more functions

main.js:

var foo = require('module.js')(firstParam);
var bar = require('module.js')(secondParam);

我的问题是,firstParam是一个对象类型和secondParam是一个URL字符串,但当我有它总是抱怨类型是错误的。

我如何声明多个模块。在这种情况下出口?


当前回答

module1.js:

var myFunctions = { 
    myfunc1:function(){
    },
    myfunc2:function(){
    },
    myfunc3:function(){
    },
}
module.exports=myFunctions;

main.js

var myModule = require('./module1');
myModule.myfunc1(); //calling myfunc1 from module
myModule.myfunc2(); //calling myfunc2 from module
myModule.myfunc3(); //calling myfunc3 from module

其他回答

module.exports = (function () {
    'use strict';

    var foo = function () {
        return {
            public_method: function () {}
        };
    };

    var bar = function () {
        return {
            public_method: function () {}
        };
    };

    return {
        module_a: foo,
        module_b: bar
    };
}());

在你的节点模块中,你可以导出各种函数,比如:

Module.exports.eat =吃; 函数eat() { …… 返回* *的东西; }; Module.exports.sleep =睡眠; 函数sleep() { …… 返回* *的东西; };

注意,导出函数时并没有调用它们。 然后,在要求模块时,您可以要求为:-

Const task = require(__dirname + "/task.js"); //task是文件的名称 Let eat = task.eat(); Let sleep = task.sleep();

你可以像我下面做的那样…对于函数和箭头函数:

greet.js:

函数greetFromGreet() { Console.log ("hello from greet module…"); } const greetVar = () => { Console.log("将var视为箭头fn/…"); }; 模块。exports = {greetVar, greetFromGreet};// ----多个模块导出…

// -----------------------------------------------

app.js:

const greetFromGreets = require("./greet");

greetFromGreets.greetFromGreet();
greetFromGreets.greetVar();

// -----------------------------------------------

使用export关键字

module.js

export {method1, method2}

然后导入到main.js中

import {method1, method2) from "./module"

要导出多个函数,你可以像这样列出它们:

module.exports = {
   function1,
   function2,
   function3
}

然后在另一个文件中访问它们:

var myFunctions = require("./lib/file.js")

然后你可以通过调用:

myFunctions.function1
myFunctions.function2
myFunctions.function3