Home > Software engineering >  How to call a function (in separate file) from http callback function. app.get("/", callba
How to call a function (in separate file) from http callback function. app.get("/", callba

Time:04-23

File structure:

testAPI
    contactDetail
        dispMobNo.js
        myModule.js
index.js

index.js

const express = require("express");
const app = express();
const port = process.env.port || 3000;
const getCustNo = require("./contactDetail/dispMobNo");
app.use(getCustNo);

app.listen(port, console.log("server running on port: "   port));

dispMobNo.js

const express = require("express");
const router = express.Router();
router.get("/", getContactNo);

function getContactNo(req, res)
{
    console.log(req.query);
    res.send(req.query);
}
module.exports = router;

Above code is working BUT I want to remove getContactNo function from this file and want to put it in a separate file. I mean, I don’t want to put any code inside/under API endpoint. I want to put getContactNo function in separate file and want to call from API endpointcallback function. So, how to do this?

Modified version of dispMobNo.js:

const express = require("express");
const router = express.Router();
router.get("/", getContactNo);
module.exports = router;

myModule.js

function getContactNo(req, res)
{
    console.log(req.query);
    res.send(req.query);
}
module.exports = getContactNo;

CodePudding user response:

you can do this way

  1. create one controller file in which create and export all your business logic functions.

// controller.js file

export async getData = (req) => {

// your logic


}

  1. import that controller file in your route file, and use function there.

// route.js file
const Controller = require("./controller");

route.get('/api-endpoint',async(req,res)=>{
  Controller.getData();
})

CodePudding user response:

You are almost there.

Modified version of dispMobNo.js:

const myModule = require('./my-module.js');
const express = require("express");
const router = express.Router();
router.get("/", myModule.getContactNo);
module.exports = router;

my-module.js

function getContactNo(req, res)
{
    console.log(req.query);
    res.send(req.query);
}
module.exports = {
  getContactNo
};

Above, I have assumed that, both files are in same directory.

  • Related