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

标签 node.js testing command-line exec testcafe

我一直在寻找一个真正的例子,但我找不到。我对 Node js 完全陌生。

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

命令行“pw get key”返回与 key 关联的密码。 命令行“pw set key password”设置与 key 关联的密码。

到目前为止我拥有的部分代码是:

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 环境中使用。这里我定义了一个角色。

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 代码就可以工作。

/缺失的位/留空,因为我尝试了很多不同的方法,但没有人成功!

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

有什么建议吗?我知道这确实是为了理解node.js中的promise之类的东西,但我无法摆脱这个。

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

最佳答案

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

cmdPwGet的执行结果是一个promise

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

make getPw 异步/等待

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

关于node.js - Node js : I to get the output of an (child) exec and set a variable to be retuned?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47613481/

相关文章:

node.js - Node postgres 池管理

typescript - 使用 Jest/Typescript 和虚拟函数测试 fs 库函数

c - 如果有任何未发现的错误,如何测试字数统计程序?

linux - 如何在 Linux 中打开一个程序的多个实例

bash - 如何获取内置命令的内置?

javascript - 为什么即使在使用 async await 多次调用之后仍然得到空响应?

javascript - 如何在 Atom-Shell 中运行 reload() 和 open()

linux - 将一个命令的输出重定向到多个命令

node.js - 使用 NCONF 捕获命令行参数

git - 如何 Jest 使用 --changedSince 和 --onlyChanged?