Home > Software design >  Call a function from module.exports and give value to its parameter
Call a function from module.exports and give value to its parameter

Time:09-03

I am building NodeJS code that listens to requests from specific ports and returns a response to it, here is the main code:

module.exports = function (port) {
    var fs            = require("fs");
    var path          = require("path");
    var express       = require('express');
    var vhost         = require('vhost');
    var https         = require('https');
    var http          = require('http');
    var bodyParser    = require("body-parser");
    
    var normalizedPath = require("path").join(__dirname, "../BlazeData/ssl/");
    
    var options = {
        key: fs.readFileSync(normalizedPath   'spring14.key'),
        cert: fs.readFileSync(normalizedPath   'spring14.cert'),
    };

    var app = express();
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());

    var normalizedPath = path.join(__dirname, "../WebServices");
    fs.readdirSync(normalizedPath).forEach(function(file) {
        if (file.indexOf('.js') != -1) {
            var url = file.substring(0, file.length - 3);
            app.use(vhost(url, require(normalizedPath "/" file).app));
            
            console.log( 'Registered Service -> %s:%d', url, port );
        }
    });
    
    if (port == 80) {
        var server = http.createServer(app).listen(port, function(){
            console.log("Create HTTP WebServices");
            console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
        });
    }
    
    if (port == 443) {
        var server = https.createServer(options, app).listen(port, function(){
            console.log("Create HTTPS WebServices");
            console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
        });
    }
    
}

I have another JS file that is used to run the script above, I use var https1 = require('./clientAuthServer') to initiate the code from above where clientAuthServer.js is the filename of the main code, however it just skips everything from that file.

How would I call module.exports = function (port) from a separate file and give a value to the parameter "port" which the function is using?

CodePudding user response:

When you require your module it returns a function (the function exported by the module). The function is being assigned to the variable https1, so you simply need to call that function because right now it's just being stored.

The simplest way would be for your require statement to look something like this:

const https1 = require("./clientAuthServer")(parameter);

Where parameter is just whatever value you want to pass to the function.

  • Related