【问题标题】:how access any function from module in nodejs?如何从nodejs中的模块访问任何功能?
【发布时间】:2020-07-25 19:56:16
【问题描述】:

我在 nodejs 中使用 restify 框架创建了一个服务器,但是当我想从 Function.js 执行 respond() 功能时,它会打印输出'hello undefined' 实际上 预期的输出是 'hello world',我认为 Function.js 的另一个函数正在影响 ...告诉我如何我们从模块中访问特定的功能?

server.js

var restify=require('restify')
var respond=require("./src/Components/FunctionalComponents/Function")
var server=restify.createServer() //server created


server.get('/hellopj',respond);

server.listen(8080, function(){
    console.log("server started...")
})

Function.js

module.exports =function respond(req,res,next){
        res.send('hello world ')
}

module.exports =function insertFun(req,res,next){
    res.send('hello '+req.params.name)
}

【问题讨论】:

  • 试试,respond.respond in server.get?

标签: node.js restify


【解决方案1】:

Nodejs中有两种导出模块的方式。

  • 默认导出(一次没有任何键)
  • 命名导出。 (一次用钥匙)

现在,您正在使用默认导出,它被最后一个 insertFun 导出替换,因为每个文件只能有一个默认导出。

对于命名导出,只需给每个导出一个密钥并使用该密钥导入即可。

Functions.js:

module.exports ={
   respond: function respond(req,res,next){
       res.send('hello world ');
   },
   insertFun: function insertFun(req,res,next){
       res.send('hello '+req.params.name)
   }
};

Server.js:

const { respond } = require("./src/Components/FunctionalComponents/Function");

//......

server.get('/hellopj', respond);

//.....

【讨论】:

  • 如果我想使用这个 insertFun() 在表中插入数据,我应该在 Function.js 中写什么?
  • 只需导出 insertFun 从类似于 response .const { respond, insertFun } = require("./src/Components/FunctionalComponents/Function");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
相关资源
最近更新 更多