【问题标题】:why some module creation require us to include () and some don't in node js?为什么有些模块创建需要我们包含 () 而有些则不需要在节点 js 中?
【发布时间】:2021-07-23 02:49:41
【问题描述】:

如果我想为超级英雄 npm 创建一个名为“a”的模块,我可以不带括号声明它



var a = superheroes; //no parenthesis


var randomSuperHero = a.random();

如果我想为 express npm 创建一个名为 app 的模块,我需要包含一组括号。

const express = require('express')
 

const app = express(); //parenthesis


app.get("/",function(req,res){

res.send("Hello World!")

})

为什么会这样?

另外,在这行特定的代码中,

app.get("/",function(req,res){

它怎么知道第一个参数是请求,第二个参数是响应? 我是新手,所有这些小事情都让我感到困惑。

【问题讨论】:

  • 这取决于模块导出对象或函数的天气。节点模块可以导出任何东西。如果那个“东西”是一个字符串,那么那个模块就是一个字符串,你把它当作一个字符串(字符串不能被调用,所以你不能添加())。如果该模块是一个数字,那么它就是一个数字。如果该模块是一个对象,那么它就是一个对象.. 你看我要去哪里。如果该模块是一个函数,那么它就是一个函数。您可以通过添加() 来调用函数,例如console.log()

标签: node.js express npm


【解决方案1】:

一些npm 模块在顶层导出要执行的函数以构造实例。

以express-js,

From the API documentation

express() - 创建一个 Express 应用程序。 express() 函数是由 express 模块导出的顶级函数。

让我们看一下superhero 模块。 The index.js file exports two properties,

  • 随机,一个函数
  • 所有,一个 json blob
const supe = require('superheroes');
const everyHero = supe.all //will give the contents of superhero.json
const randomOne = supe.random() // is an exported function
// calling supe() will throw an error as that is not an exported function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多