javascriptnode.jsfunctiondebuggingjavascript-objects

I have function calling anther function to return string, but I get undefined. because of the read file implement first


I'm not that expert, but I can handle it: this calling the function checkTLS

// params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  

Object.keys(params).forEach( key => {
    console.log(key);
    if(key.includes("tls")){ 
        //splitting parms to get cluster id
        clusterId=key.substring(0, key.indexOf("_"));
        console.log("cluster ID=="+clusterId);
        tlsresualt= checkTLS(clusterId);
        console.log("tls resualt is="+ tlsresualt);
        req.body[`${clusterId}_tls`]=tlsresualt;
        console.log(req.body.ibmdev_tls);
        console.log("==================================");
    }
});

The checktlsStatus is what I need to pass:

function checkTLS(clusterID){
    fs.readFile("clusterinfo/clusterinfo.json",(err, clusters) => {
        TlsVerion="TLS12";
        if(TlsVerion.includes("TLS12")){ 
            console.log(`TLs check status ------------------------ for ${clusterID}`);
            console.log(` TLs match the Secuity Baseline requirment for ${clusterID}`);
            checktlsStatus="implemented";
            //req.body.ibmdevtls=tlsStatus;
            //return console.log(checktlsStatur+ "check for tls successed");
            // req.body.(`${clusterID}`+`tls`)=tlsStatus;
            return checktlsStatus;
        }
    )};
}

I have tried await and asycn , also execSync(sleep 20);


Solution

  • Callback doesn't work that way!

    Think about this:

    function foo(name, callback) {
      callback(name.length);
    }
    
    function bar() {
      const abc = foo("something", (n) => {
        return n + 10;
      });
      console.log(abc);
    }
    
    bar();

    The abc will always undefined because foo has no return value!

    The callback return value is omitted by foo.

    This is how you think fs.readFile works. But it not work like that way!


    There is someways to solve it:

    1. Add a callback to checkTLS function.
    2. Use fs.readFileSync.
    3. (Recommand)Use Promise(async/await) API.

    Let's do it:

    const fs = require("fs");
    params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  
    
    Object.keys(params).forEach(async (key) => {
        console.log(key);
        if(key.includes("tls")){ 
            //splitting parms to get cluster id
            clusterId=key.substring(0, key.indexOf("_"));
            console.log("cluster ID=="+clusterId);
            // this changed
            const tlsresualt = await checkTLS(clusterId);
            console.log("tls resualt is="+ tlsresualt);
            // req.body[`${clusterId}_tls`]=tlsresualt;
            // console.log(req.body.ibmdev_tls);
            console.log("==================================");
        }
    });
    
    async function checkTLS(clusterID){
        const clusters = await fs.promises.readFile("clusterinfo/clusterinfo.json");
        TlsVerion="TLS12";
        if(TlsVerion.includes("TLS12")){ 
            console.log(`TLs check status ------------------------ for ${clusterID}`);
            console.log(` TLS match the Security Baseline requirement for ${clusterID}`);
            checktlsStatus="implemented";
            //req.body.ibmdevtls=tlsStatus;
            //return console.log(checktlsStatur+ "check for tls succeeded");
            // req.body.(`${clusterID}`+`tls`)=tlsStatus;
            return checktlsStatus;
        }
    }
    
    

    I'm not sure what you want to do. So just remake checkTLS to an async function.


    I recommend to use fs.promises and async/await, if you don't want it. Try this:

    const fs = require("fs");
    
    params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  
    
    Object.keys(params).forEach( key => {
        console.log(key);
        if(key.includes("tls")){ 
            //splitting parms to get cluster id
            clusterId=key.substring(0, key.indexOf("_"));
            console.log("cluster ID=="+clusterId);
            // this changed
            checkTLS(clusterId)
                .then(tlsresult => {
                    console.log("tls result is="+ tlsresult);
                    // req.body[`${clusterId}_tls`]=tlsresult;
                    // console.log(req.body.ibmdev_tls);
                    console.log("==================================");
                });
        }
    });
    
    function checkTLS(clusterID){
        return new Promise(resolve => {
            fs.readFile("clusterinfo/clusterinfo.json",(err, clusters) => {
                TlsVerion="TLS12";
                if(TlsVerion.includes("TLS12")){ 
                    console.log(`TLs check status ------------------------ for ${clusterID}`);
                    console.log(` TLS match the Security Baseline requirement for ${clusterID}`);
                    checktlsStatus="implemented";
                    //req.body.ibmdevtls=tlsStatus;
                    //return console.log(checktlsStatur+ "check for tls succeeded");
                    // req.body.(`${clusterID}`+`tls`)=tlsStatus;
                    resolve(checktlsStatus);
                }
            });
        });
    }
    

    References: