0

我一直在试图了解 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 开始工作。这完全是出于好奇

谢谢

4

1 回答 1

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'
于 2019-09-08T10:36:39.853 回答