UNPKG

pauls-dat-api

Version:

Library of functions that make working with dat / hyperdrive easier.

41 lines (28 loc) 2.29 kB
'use strict';function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};}var path = require('path');var _require = require('beaker-error-constants'),NotFoundError = _require.NotFoundError;var _require2 = require('./common'),maybe = _require2.maybe;var _require3 = require('./lookup'),stat = _require3.stat;var _require4 = require('./read'),readdir = _require4.readdir; // download the given file(s) function download(archive, name, cb) { return maybe(cb, _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {var entry, listing, promises;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_context.next = 2;return ( stat(archive, name));case 2:entry = _context.sent;if ( entry) {_context.next = 5;break;}throw ( new NotFoundError(`The entry ${name} was not found in the archive.`));case 5:if (! entry.isDirectory()) {_context.next = 11;break;}_context.next = 8;return ( readdir(archive, name));case 8:listing = _context.sent; promises = listing.map(function (subname) {return download(archive, path.join(name, subname));});return _context.abrupt('return', Promise.all(promises));case 11:if (! entry.isFile()) {_context.next = 15;break;}if (!( entry.downloaded === entry.blocks)) {_context.next = 14;break;}return _context.abrupt('return');case 14:return _context.abrupt('return', new Promise(function (resolve, reject) { archive.content.download({ start: entry.offset, end: entry.offset + entry.blocks }, function (err) { if (err) reject(err);else resolve(); }); }));case 15:case 'end':return _context.stop();}}}, _callee, this);}))); } module.exports = { download };