hostr/lib/hostr-file-stream.js

52 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-07-09 23:01:43 +01:00
import fs from 'fs';
import createError from 'http-errors';
2016-06-06 13:39:42 +01:00
import { get as getSFTP } from './sftp';
import { get as getS3 } from './s3';
2015-07-09 23:01:43 +01:00
import debugname from 'debug';
const debug = debugname('hostr:file-stream');
2016-06-06 13:39:42 +01:00
function writer(localPath, remoteRead) {
2015-07-09 23:01:43 +01:00
return new Promise((resolve, reject) => {
2016-06-06 13:39:42 +01:00
remoteRead.once('error', () => {
debug('remote error');
reject(createError(404));
});
const localWrite = fs.createWriteStream(localPath);
localWrite.once('finish', () => {
debug('local write end');
resolve(fs.createReadStream(localPath));
});
2015-07-09 23:01:43 +01:00
2016-06-06 13:39:42 +01:00
remoteRead.once('readable', () => {
debug('writing');
remoteRead.pipe(localWrite);
});
});
}
2015-07-09 23:01:43 +01:00
2016-06-06 13:39:42 +01:00
export default function hostrFileStream(localPath, remotePath) {
const localRead = fs.createReadStream(localPath);
return new Promise((resolve, reject) => {
localRead.once('error', () => {
debug('not found locally');
getSFTP(remotePath)
.then((remoteRead) => writer(localPath, remoteRead))
.then(resolve)
.catch((err) => {
debug('not on sftp', err);
writer(localPath, getS3(remotePath))
.then(resolve)
.catch((s3err) => {
debug('not on s3');
reject(s3err);
});
2016-05-25 21:03:07 +01:00
});
2015-07-09 23:01:43 +01:00
});
localRead.once('readable', () => {
2016-06-06 13:39:42 +01:00
debug('found locally');
2015-07-09 23:01:43 +01:00
resolve(localRead);
});
});
}