node.jsrestify

how access any function from module in nodejs?


I create a server using restify framework in nodejs, but when i want to respond() funtion from Function.js it prints output 'hello undefined' actully expected output is 'hello world', i think another function from Function.js is affecting ... tell me how we access particular function from module?

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)
}

Solution

  • There are two ways to export module in Nodejs.

    Right now, you are using default export which is being replaced by the last insertFun export as each file can have only one default export.

    For Named Export, Just give each export a key and import with that key and you are good to go.

    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);
    
    //.....