-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsftp.js
39 lines (32 loc) · 1.38 KB
/
sftp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const fs = require('fs');
const { Client } = require('ssh2');
const findLeastLoadedServer = require("./loadBalance");
async function uploadZipFile(localFilePath, remoteFilePath, serverDataFilePath) {
try {
const leastLoadedServer = await findLeastLoadedServer(serverDataFilePath);
const conn = new Client();
conn.on('ready', () => {
conn.sftp((err, sftp) => {
if (err) throw err;
const readStream = fs.createReadStream(localFilePath);
const writeStream = sftp.createWriteStream(remoteFilePath);
readStream.pipe(writeStream);
writeStream.on('close', () => {
console.log(`File uploaded successfully to ${leastLoadedServer.server_name}: ${remoteFilePath}`);
conn.end();
});
writeStream.on('error', (error) => {
console.error(`Error uploading file to ${leastLoadedServer.server_name}: ${error}`);
conn.end();
});
});
}).connect({
host: leastLoadedServer.host,
username: leastLoadedServer.creds.user,
privateKey: fs.readFileSync(leastLoadedServer.creds.privateKey)
});
} catch (error) {
console.error('Error:', error);
}
}
module.exports = uploadZipFile;