node.js - 如何在 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();
解决方案
您不需要使用承诺,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)
推荐阅读
- sql - 没有与 SQL 'WHERE' 子句一起使用的运算符?
- pagination - 如何在 GraphQL 中强制分页
- excel - phpspreadsheet setFormatCode 性能问题
- python - 如何定义文件 .exe 读取的多个参数?
- hyperledger-fabric - 隐式策略评估失败 - 满足 1 个子策略,但此策略需要满足 2 个“背书”子策略
- python - 无法在 http://localhost:5000 访问 Dockerized Flask 应用程序
- c++ - `std::async` 用于 C++ 中的异步回复
- vhdl - 为什么这个 vhdl 代码会陷入无限循环?
- pybind11 - 在绑定自定义类型时,我还必须绑定自定义类型 API 中显示的所有其他类型吗?
- reactjs - React Material UI KeyboardDateTimePicjer 上的 maxDate 有问题