hostr/lib/sftp.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-06-06 13:39:42 +01:00
import { dirname, join } from 'path';
import Client from './ssh2-sftp-client';
2016-05-25 21:03:07 +01:00
import debugname from 'debug';
const debug = debugname('hostr:sftp');
export function get(remotePath) {
2016-06-06 13:39:42 +01:00
debug('fetching', join('hostr', 'uploads', remotePath));
2016-05-25 21:03:07 +01:00
const sftp = new Client();
return sftp.connect({
host: process.env.SFTP_HOST,
port: process.env.SFTP_PORT,
username: process.env.SFTP_USERNAME,
password: process.env.SFTP_PASSWORD,
2016-06-06 13:39:42 +01:00
})
.then(() => sftp.get(join('hostr', 'uploads', remotePath), { encoding: null }));
2016-05-25 21:03:07 +01:00
}
2016-06-06 20:57:34 +01:00
function sendFile(localPath, remotePath) {
2016-05-25 21:03:07 +01:00
const sftp = new Client();
return sftp.connect({
host: process.env.SFTP_HOST,
port: process.env.SFTP_PORT,
username: process.env.SFTP_USERNAME,
password: process.env.SFTP_PASSWORD,
2016-06-06 13:39:42 +01:00
})
.then(() => sftp.put(localPath, remotePath, true))
2016-06-06 20:57:34 +01:00
.catch((err) => {
if (err.message === 'No such file') {
debug('Creating directory');
return sftp.mkdir(dirname(remotePath), true)
.then(() => sftp.put(localPath, remotePath, true));
}
throw err;
});
}
export function *upload(localPath, remotePath) {
let done = false;
for (let retries = 0; retries < 5; retries++) {
try {
done = yield sendFile(localPath, remotePath);
break;
} catch (err) {
debug('retry');
}
}
return done;
2016-05-25 21:03:07 +01:00
}