hostr/lib/hostr-file-stream.js

43 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2015-07-09 23:01:43 +01:00
import fs from 'fs';
import createError from 'http-errors';
2018-06-02 18:07:00 +00:00
import debugname from 'debug';
2018-06-02 15:50:39 +00:00
import { get as getS3 } from './s3';
2015-07-09 23:01:43 +01:00
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) => {
2018-06-02 15:50:39 +00:00
const localWrite = fs.createWriteStream(localPath);
remoteRead.once('error', (err) => {
debug('remote error', err);
2016-06-06 13:39:42 +01:00
reject(createError(404));
});
2018-06-02 15:50:39 +00:00
2016-06-06 13:39:42 +01:00
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');
2018-06-02 15:50:39 +00:00
writer(localPath, getS3(remotePath)).then((readable) => {
resolve(readable);
}).catch(reject);
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);
});
});
}