我正在使用ssh2连接到远程sftp服务器。代码如下所示:
fetchFileList() {
return new Promise((resolve, reject) => {
const sshClient = new Client();
let isReady = false;
logger.info("fetchFileList making SF connection");
sshClient.on("ready", () => {
isReady = true;
logger.info("Ready");
sshClient.sftp((err, sftp) => {
if (err) {
logger.error("Some error occoured ", { err });
reject("Error establishing sftp connection");
}
logger.info("Sftp connection is successful");
sftp.readdir(CONST.EXTRACT.FTP_DIRECTORY, (err, files) => {
if (err) {
reject(new CustomError("Sftp read dir", err));
}
// Read all file 'formats' from entity db
sortFilesByTables(files)
.then(result => {
resolve({ sshClient, sftp, result });
})
.catch(err => {
reject(new CustomError("Error sorting files by tables ", err));
});
});
});
});
sshClient.on("error", err => {
logger.error("Error connecting to sftp server ", err);
webHook
.send(
utils.composeSlackMessage(
"Error connecting to sftp server",
CONST.EXPORT.SLACK_MESSAGE_TYPES.ERROR,
err
)
)
.catch(err => logger.error("Webkook catch ", err));
reject(new CustomError("Error connecting to sftp server ", err));
});
sshClient.on("end", () => {
if (!isReady) {
logger.error(
"fetchFileList on end Callback could not establish sftp connection"
);
reject(
"fetchFileList on end Callback could not establish sftp connection"
);
}
});
sshClient.connect({
host: ftpCredentials.host,
port: ftpCredentials.port,
username: ftpCredentials.username,
password: ftpCredentials.password,
readyTimeout: 90000
});
});
}
有时尝试连接时,将调用end回调,但不会调用错误或ready回调。有谁知道为什么会这样?无法与sftp服务器建立连接时,是否应该发生错误回调? (以前我只有就绪和错误回调,在这种情况下,都没有被调用,并且服务器程序挂在该promise中)。
我正在使用的节点模块是"ssh2": "^0.6.1"
,