首页 > 解决方案 > 如何在 ssh-exec 中使用 await/async?

问题描述

我正在尝试使用 ssh 运行命令,但我得到的值不确定如何在此处使用 await 和 async,以便在将数据保存到 DB 后我可以关闭线程

require('dotenv').config()

const db = require('../lib/db');
const exec = require('ssh-exec')

var getModems = new Promise(function(resolve, reject) {
  var v_host = '122.12.19.160'
  exec('proxysmart-remote.sh list_online_modems', {
    user: 'root',
    host: v_host
  }).pipe(process.stdout , function (err, data) {
    resolve(data);
  })
});


const saveModems = function () {
  getModems.then(function(value) {
    // save into db
    console.log(value);
  });
}

saveModems()
process.exit();

标签: node.jsexpress

解决方案


您不需要使用承诺,ssh-exec 返回一个流,您可以将函数绑定到一些流事件,例如:

let acc = '' // This is the variable where we accumulate every chunk of the stream.
exec('something')
  .on('data', function(chunk) {
    acc = acc + chunk
  })
  .on('close', function() {
    db.save(acc) // or do whatever you need.
    db.close() // Here we close the database connection how is supposed to be done.
  })
  .pipe(process.stdout)

推荐阅读