NodeJS 我有函数调用另一个函数返回字符串,但我得到未定义.因为读文件实现第一[重复]

0yg35tkg  于 2023-03-08  发布在  Node.js
关注(0)|答案(2)|浏览(94)
    • 此问题在此处已有答案**:

(41个答案)
昨天关门了。
我不是Maven,但我能搞定:调用函数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("==================================");
    }
});
    • checktlsStatus**是我需要传递的内容:
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;
        }
    )};
}

我试过wait和asycn,也试过execSync(sleep 20);

62lalag4

62lalag41#

回拨不是这样的!
想想看:

function foo(name, callback) {
  callback(name.length);
}

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

bar();

因为foo没有返回值,所以abc总是未定义的!
foo忽略了回调返回值。
这就是你认为fs.readFile是如何工作的。但它不是那样工作的!
有一些方法可以解决它:
1.向checkTLS函数添加回调。
1.使用fs.readFileSync
1.(建议)使用Promise(异步/等待)API。
我们开始吧:

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

我不确定你想做什么,所以只要把checkTLS重新编译成一个异步函数就行了。
如果你不想使用fs.promisesasync/await,我推荐使用它们。

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(tlsresualt => {
                console.log("tls resualt is="+ tlsresualt);
                // req.body[`${clusterId}_tls`]=tlsresualt;
                // 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 Secuity Baseline requirment for ${clusterID}`);
                checktlsStatus="implemented";
                //req.body.ibmdevtls=tlsStatus;
                //return console.log(checktlsStatur+ "check for tls successed");
                // req.body.(`${clusterID}`+`tls`)=tlsStatus;
                resolve(checktlsStatus);
            }
        });
    });
}

参考文献:

lzfw57am

lzfw57am2#

我已经修改了你的代码与相同的功能使用异步和等待。内容变量有读文件的内容。

const fs = require('fs')
    const util = require('util')`enter code here`
    const readFileContent = util.promisify(fs.readFile)
    const fetchFile = async (path,clusterID) => {
    const buff = await readFileContent(path)

    const contents = buff.toString()
    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";
          return checktlsStatus;
      }
      console.log(`\nContents of the file :`)
    }
       

    async function neo(){
        params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  

        for (const property in params) {
            console.log(property);
            if(property.includes("tls")){ 
                //splitting parms to get cluster id
                clusterId=property.substring(0, property.indexOf("_"));
                console.log("cluster ID=="+clusterId);
                tlsresualt = await fetchFile('file.json',clusterId);
                console.log("tls resualt is="+ tlsresualt);
                console.log("==================================");
        }
        }
    }

    neo()

参照Here,详细说明可参照

相关问题