【问题标题】:Understanding module.export to pass a parameter了解 module.export 以传递参数
【发布时间】:2019-09-08 10:02:11
【问题描述】:

我一直在尝试理解,module.export 如何用它传递参数。现在我已经制作了一个演示服务器来测试它。

文件 - index.js

var express = require('express');
var check = require('./file');
var app = express();

app.get('/',check.fun1("calling"),(req,res)=>{
    res.send('here i am');
})

app.listen(3000,()=>{
    console.log("Server is up");
})

通过中间件检查,

module.exports = fun1 = name => {
    return function(req, res, next) {
      console.log(name + " from fun1");
      next();
    };
  };

  module.exports = fun2 = name2 => {
    return function(req, res, next) {
      console.log(name + " from fun1");
      next();
    };
  };

现在这不起作用,但是当我更改它时,它开始起作用了

fun1 = name => {
  return function(req, res, next) {
    console.log(name + " from fun1");
    next();
  };
};

fun2 = name2 => {
  return function(req, res, next) {
    console.log(name + " from fun1");
    next();
  };
};

module.exports = {
  fun1,
  fun2
};

现在,这可能看起来像一个愚蠢的问题,如果它有效,那么我为什么要问,但是,我应该在 index.js 文件中进行哪些更改,以便我的第一种 module.export 类型开始工作。纯粹出于好奇

谢谢

【问题讨论】:

  • 您希望module.exports = fun1 = name => {...} 做什么? fun1 这里的目的是什么?如果你想从你的模块中导出两个函数,那么你写exports.fun1 = name => {...}exports.fun2 = name2 => {...}。如果要导出单个值,则仅覆盖 module.exports。不确定问题的标题与您的问题有何关系。
  • 好的,我现在明白了,exports.mdoule 基本上是模块中的一个 obj,如果我将它导出两次,它就会被覆盖,嗯,有道理。但是exports直接转换成module.export hmmm..thankx
  • exports 只是模块范围内的一个变量,最初引用的值与module.exports 相同。

标签: node.js module.exports


【解决方案1】:

node.js 中的很多东西都是简单的设计模式。 Node.js 在最初发布时对 javascript 引入了零扩展(这包括它的模块系统)。即使在今天,node.js 也有零语法扩展。 Node.js 只是带有附加库和特殊运行时环境的 javascript(所有模块都在 IIFE 中进行评估)

话虽如此,module.exports 不是语法。它只是javascript中的一个普通变量。具体来说,变量module 是一个对象,节点的模块系统将检查这个module 变量,看它是否有一个名为exports 的属性。如果module 具有exports 属性,则其值将被视为导出的模块。

由于module 只是一个普通变量,它遵循正常的变量行为。如果你重新分配一个变量,它的值将会改变。例如:

var x = 0;
console.log(x); // prints 0;
x = 100;
console.log(x); // prints 100, not 0 and 100

因此,module.exports 也是如此:

module.exports = 'hello';
console.log(module.exports); // prints 'hello'
module.exports = 'world';
console.log(module.exports); // prints 'world', not 'hello world'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多