nodejs:事件监听器代码使它asynn等待得到承诺响应返回



我有以下代码

const { readFileSync } = require('fs');
const { Client } = require('ssh2');
// console.log(filename)
const conn = new Client();
conn.on('ready', () => {

console.log('Client :: ready');
console.log("We will execute the file " + filename);
conn.exec('python ~/test.py', (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data); //I want this data outside of the whole scope
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'x.x.x.x',
port: 22,
username: 'abc',
privateKey: readFileSync('./id_rsa')
});

在外面如果我输入console.log(data)它不会输出任何内容

我是node js中的新成员,我如何才能获得执行结果STDOUT:python test.py的数据到方法外部

任何帮助都是非常感激的

一种方法是将代码包装在承诺中:

function execScript() {
return new Promise((resolve, reject) => {
conn.on('ready', () => {     
console.log('Client :: ready');
console.log("We will execute the file " + filename);
conn.exec('python ~/test.py', (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data); //I want this data outside of the whole scope
resolve(data.toString());
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'x.x.x.x',
port: 22,
username: 'abc',
privateKey: readFileSync('./id_rsa')
});
});
}
(async () => {
const scriptStdout = await execScript();
console.log(scriptStdout); // This should be STDOUT
})();

相关内容

  • 没有找到相关文章

最新更新