为了显示用户发送到集群的作业,我有以下代码(简化):
var split = require('split');
var Client = require('ssh2').Client;
var conn = new Client();
var globalRes;
var table = [["Head_1","Head_2"]];
module.exports = {
renderTable: function(req, res) {
conn.connect({host: 'xx.xx.xx.xx', port: 22, username: 'xxxxx', password: 'xxxxx'});
globalRes = res;
table = [["Head_1","Head_2"]];
conn.on('ready', function() { conn.shell(doSomething);} );
}
}
function doSomething(err, stream) {
stream.on('close', function() {
conn.end();
globalRes.render('index', { HTMLtable: table });
console.log(table);
} );
stream.pipe(split()).on('data', buildTable);
stream.write('qstat -s z\n');
stream.end('exit\n');
}
function buildTable(line) {
var newLine = [1, 2];
if(line.substring(0,6) == "job-ID") {
table.push(newLine);
}
return;
}
它打开一个 ssh 连接,收到数据后呈现页面。
问题:只有第一次才能正确执行,在我们的示例中 console.log 显示:
[ [ 'Head_1', 'Head_2' ], [ 1, 2 ] ] <<< 没问题。
但是从第一次开始,每次加载页面时,代码都会堆积在“表”数据结构上。换句话说,如果我们第二次重新加载页面(或在另一个浏览器中第一次加载同一页面)console.log 显示:
[ [ 'Head_1', 'Head_2' ], [ 1, 2 ], [ 1, 2 ] ]
[ [ 'Head_1', 'Head_2' ], [ 1, 2 ], [ 1, 2 ] ]
因此,不仅“table”获得了额外的行 [1,2](不应该),而且命令 console.log 被执行了两次。
如果我们第三次加载页面,现在我们得到:
[ [ 'Head_1', 'Head_2' ], [ 1, 2 ], [ 1, 2 ], [ 1, 2 ] ]
[ [ 'Head_1', 'Head_2' ], [ 1, 2 ], [ 1, 2 ], [ 1, 2 ] ]
[ [ 'Head_1', 'Head_2' ], [ 1, 2 ], [ 1, 2 ], [ 1, 2 ] ]
“table”随着 console.log 的执行次数而增长。
预先感谢您提供的任何帮助。
最佳答案
好的,问题解决了。我发帖是为了防止其他人遇到类似的问题,这可能会有所启发。
这是由于我的 Javascript 编码实践不当造成的。如果您将所有内容包含在 renderTable 函数中,它就会起作用,这是零 (0) 个全局变量。
里面的所有函数、所有变量(重要:包括“require()”):
module.exports = {
renderTable: function(req, res) {
<<<< Put everything here.
}
}
事实上,这样变量'globalRes'是不必要的,只需使用'res'即可。
希望这有帮助。我不会将自己的答案标记为正确,因此如果有人想了解技术并解释失败的具体原因,我会检查该答案是否正确。
关于javascript - Node js : Express + ssh2 does NOT reset my data structures when loading web pages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35135615/