-1

When calling a function from a module.exports function to a module.exports function it script runs it runs the function that is bring ran from module.exports then in node.js throws an error saying that the function does not exist even though it has been ran.

main.js

"use strict";

//Stuff that is required for things to work or it wont work.
const battlegrounds = require('battlegrounds');
const math = require('mathjs');
const fs = require('fs');

var config, api, argv = false;
if (fs.existsSync("config.json")) {
    config = require('./config.json');
    api = new battlegrounds(config.api_key);
    argv = process.argv;
    require('./modules/misc.js').startPUBGNode(config, argv);
} else { console.error("config.json does not exist, please create it or redownload from github <3"); process.exit() }

./modules/misc.js

module.exports.startPUBGNode = function(config, argv) {
    if (config.api_key === "not_set") {
        require('./cmd.js').prog_setup();
    } else {
        switch (argv[2].split("\r").join("")) {
            case '-m':
            case '--export-match-data':
                require('./cmd.js').getmatchdata();
                break;
            case '-mu':
            case '--latest-match-from-username':
                require('./cmd.js').getlatestmatchfromusername();
                break;
            case '-mhtml':
            case '--match-export-to-html':
                require('./cmd.js').exportashtml();
                break;
            case '-muhtml':
            case '--match-export-to-html-from-username':
                require('./cmd.js').exportashtmlfromuname();
                break;
            case '-p':
            case '--get-player-info':
                require('./cmd.js').getplayerinfo();
                break;
            case '-lm':
            case '--get-latest-matchid-from-username':
                require('./cmd.js').latestmatchidfromusername();
                break;
            case '-c':
            case '--cleanup':
                require('./cmd.js').cleanup();
                break;
            case '-s':
            case '--setup':
                require('./cmd.js').setup();
                break;
            case '-h':
            case '--help':
                require('./cmd.js').help();
                break;
            default:
                console.log("No Valid Arguments Recognised, Try './tool --help' or 'node require('./cmd.js').js --help'");
                process.exit();
                break;
        }
    }
}

./modules/cmd.js (./cmd.js in ./modules/misc.js)

const math = require('mathjs');
const battlegrounds = require('battlegrounds');
var argv = process.argv;

var  prog_setup = function(){

    const readline = require("readline");
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    console.log("Welcome to the PUBG-Node Setup, All i'll be asking for is the PUBG API Key,")
    console.log("A link to where you can find it is here; https://developer.pubg.com/")
    console.log("Click on 'Get Your own API Key' and follow the instructions.")
    console.log("\nOnce that is done please paste your key in here and press enter so\nI can validate it!")

    rl.question("API Key: ", async function (key_given) {
        const testapi = new battlegrounds(key_given);
        try {
            const res = await testapi.getPlayers({ names: ["xSuperSeed"] });
        } catch (err) {
            if (err.errors[0].title === "Unauthorized") {
                console.log("Incorrect API Key, Aborting...")
                rl.close();
            }
        }
        console.log("\n\nCongratulations!\nYour API Key is valid so its going to be saved and \nit will *overwrite* the current API Key in config.json");

        let outcontent = JSON.stringify({ "api_key": key_given });

        fs.writeFile("config.json", outcontent, function (err) {
            if (err) throw err;
            console.log('saved api key');
            rl.close();
        });
    });
}
module.exports = {
  help: help(),
  prog_setup: prog_setup(),
  latestmatchidfromusername: latestmatchidfromusername(),
  getplayerinfo: getplayerinfo(),
  cleanup: cleanup(),
  exportashtmlfromuname: exportashtmlfromuname(),
  exportashtml: exportashtml(),
  getlatestmatchfromusername: getlatestmatchfromusername(),
  getmatchdata: getmatchdata()
}

Terminal Output

Welcome to the PUBG-Node Setup, All i'll be asking for is the PUBG API Key,
A link to where you can find it is here; https://developer.pubg.com/
Click on 'Get Your own API Key' and follow the instructions.

Once that is done please paste your key in here and press enter so
I can validate it!
API Key: ## WARNING ##
This function will delete ALL match data in this directory
Are You sure? [y/N] 
/Users/ktwrd/projects/pubg-node/modules/misc.js:27
        require('./cmd.js').prog_setup();
                            ^

TypeError: require(...).prog_setup is not a function
    at Object.module.exports.startPUBGNode (/Users/jyles.coad-ward/projects/pubg-node/modules/misc.js:27:23)
    at Object.<anonymous> (/Users/jyles.coad-ward/projects/pubg-node/main.js:14:31)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

If you would like access to the github repo for more context, then here is the repo link; https://github.com/ktwrd/pubg-node

EDIT: This question was marked as a duplicate question, this is very wrong, the questions that were suggested were timing/action related (setTimeout and addEventListener) but this is more of a function related question. good first experience with stackoverflow

Kate Ward
  • 23
  • 1
  • 5
  • `prog_setup: prog_setup()` you are calling the function when assigning the property. – ASDFGerte Mar 10 '20 at 08:41
  • Just like in the linked questions, you're putting `()` after the function name, invoking it immediately, when you simply need to *pass* the function. It's the exact same sort of problem. – CertainPerformance Mar 11 '20 at 02:30

1 Answers1

0

You are calling the function when exporting the object, which is wrong in this case.

Try this.

module.exports = {
  help: help,
  prog_setup: prog_setup,
  latestmatchidfromusername: latestmatchidfromusername,
  getplayerinfo: getplayerinfo,
  cleanup: cleanup,
  exportashtmlfromuname: exportashtmlfromuname,
  exportashtml: exportashtml,
  getlatestmatchfromusername: getlatestmatchfromusername,
  getmatchdata: getmatchdata
}
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42