| 442 | } |
| 443 | |
| 444 | async get (options, searchIndex = true) { |
| 445 | let pathLocal, contentType, stats |
| 446 | try { |
| 447 | ({ path: pathLocal, contentType } = await this.resourceMapper.mapUrlToFile({ url: options, searchIndex })) |
| 448 | stats = await this.stat(pathLocal) |
| 449 | } catch (err) { |
| 450 | throw error(err.status || 500, err.message) |
| 451 | } |
| 452 | |
| 453 | if (!options.includeBody) { |
| 454 | return { stream: stats, contentType, container: stats.isDirectory() } |
| 455 | } |
| 456 | |
| 457 | if (stats.isDirectory()) { |
| 458 | const { url: absContainerUri } = await this.resourceMapper.mapFileToUrl({ path: pathLocal, hostname: options.hostname }) |
| 459 | const metaFile = await this.readContainerMeta(absContainerUri).catch(() => '') |
| 460 | let data |
| 461 | try { |
| 462 | data = await this.listContainer(pathLocal, absContainerUri, metaFile, options.hostname) |
| 463 | } catch (err) { |
| 464 | debug.handlers('GET container -- Read error:' + err.message) |
| 465 | throw err |
| 466 | } |
| 467 | const stream = stringToStream(data) |
| 468 | return { stream, contentType, container: true } |
| 469 | } else { |
| 470 | let chunksize, contentRange, start, end |
| 471 | if (options.range) { |
| 472 | const total = fs.statSync(pathLocal).size |
| 473 | const parts = options.range.replace(/bytes=/, '').split('-') |
| 474 | const partialstart = parts[0] |
| 475 | const partialend = parts[1] |
| 476 | start = parseInt(partialstart, 10) |
| 477 | end = partialend ? parseInt(partialend, 10) : total - 1 |
| 478 | chunksize = (end - start) + 1 |
| 479 | contentRange = 'bytes ' + start + '-' + end + '/' + total |
| 480 | } |
| 481 | return withLock(pathLocal, () => new Promise((resolve, reject) => { |
| 482 | const stream = fs.createReadStream(pathLocal, start && end ? { start, end } : {}) |
| 483 | stream |
| 484 | .on('error', function (err) { |
| 485 | debug.handlers(`GET -- error reading ${pathLocal}: ${err.message}`) |
| 486 | return reject(error(err, "Can't read file " + err)) |
| 487 | }) |
| 488 | .on('open', function () { |
| 489 | debug.handlers(`GET -- Reading ${pathLocal}`) |
| 490 | return resolve({ stream, contentType, container: false, contentRange, chunksize }) |
| 491 | }) |
| 492 | })) |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | async delete (url) { |
| 497 | // First check if the path points to a valid file |