节点 js:我要获取 (child) exec 的输出并设置要重新调整的变量?

node js: I to get the output of an (child) exec and set a variable to be retuned?

我一直在寻找一个真实的例子,但我找不到。我是 node js 的新手。

我正在设置一个使用命令行工具获取密码的服务。

命令行"pw get key"returns与密钥关联的密码。 命令行 "pw set key password" 设置与密钥关联的密码。

我目前掌握的部分代码是:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function cmdPwGet(key) {
  const { stdout, stderr } = await exec(`pw get ${key}`);
  console.log('stdout:', stdout); 
  console.log('stderr:', stderr);
}

async function cmdPwPut(key, passwd) {
  const { stdout, stderr } = await exec(`pw set ${key} ${passwd}`);
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}

class PwService {

    constructor (KEY){
    this.basekey = KEY;
    this.pwd = "";
    }

    setPw (key, passwd) {
      key = this.basekey + "." + key;
      var res = cmdPwPut(key, passwd);
      /* missing bits */
    }

    getPw (key) {
      key = this.basekey + "." + key;
      var res = cmdPwGet(key);
      /* missing bit */
    }
}

module.exports = PwService;

这将在 testcafe 环境中使用。这里我定义了一个Role。

testRole() {
  let pwService = new PwService('a-key-');
  let pw = pwService.getPw('testPW');
  //console.log('pw: '+pw)

  return Role('https://www.example.com/', async t => {
    await t
    .typeText(this.firstInput, 'testPW')
    .typeText(this.secondInput, pw<??>)
    .click(this.selectButton);
    }, { preserveUrl: true });
}

如果我对 pw 使用文字字符串,testcafe 代码就可以工作。

/missing bits/ 留空,因为我尝试了很多不同的方法,但没有一个成功!

我想我可以让它与 child 的 *Sync 版本一起使用。但由于这是在一个可能 运行 并行的测试咖啡馆内,我更喜欢异步版本。

有什么建议吗?我知道node.js中的promises之类的东西确实需要理解,但我无法摆脱这个

看来这应该是 node.js 专家的标准练习。

Async/Await 只是让异步代码看起来像同步代码,你的代码仍然是异步执行的。而Async\Await函数cmdPwGet的return结果是Promise,而不是你想的password

cmdPwGet 的执行结果是一个承诺

async function cmdPwGet(key) {
  const { stdout, stderr } = await exec(`pw get ${key}`);
  return stdout;
}

制作getPwAsync/Await

  async getPw(key) {
        key = this.basekey + "." + key;
        var res = await cmdPwGet(key);
        return res;
    }

获取密码

testRole() {
  let pwService = new PwService('a-key-');

  return Role('https://www.example.com/', async t => {
    // get your password with await
    let pw = await pwService.getPw('testPW');
    await t
    .typeText(this.firstInput, 'testPW')
    .typeText(this.secondInput, pw<??>)
    .click(this.selectButton);
    }, { preserveUrl: true });
}