index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. const fileType = require('file-type');
  3. const isStream = require('is-stream');
  4. const tarStream = require('tar-stream');
  5. module.exports = () => input => {
  6. if (!Buffer.isBuffer(input) && !isStream(input)) {
  7. return Promise.reject(new TypeError(`Expected a Buffer or Stream, got ${typeof input}`));
  8. }
  9. if (Buffer.isBuffer(input) && (!fileType(input) || fileType(input).ext !== 'tar')) {
  10. return Promise.resolve([]);
  11. }
  12. const extract = tarStream.extract();
  13. const files = [];
  14. extract.on('entry', (header, stream, cb) => {
  15. const chunk = [];
  16. stream.on('data', data => chunk.push(data));
  17. stream.on('end', () => {
  18. const file = {
  19. data: Buffer.concat(chunk),
  20. mode: header.mode,
  21. mtime: header.mtime,
  22. path: header.name,
  23. type: header.type
  24. };
  25. if (header.type === 'symlink' || header.type === 'link') {
  26. file.linkname = header.linkname;
  27. }
  28. files.push(file);
  29. cb();
  30. });
  31. });
  32. const promise = new Promise((resolve, reject) => {
  33. if (!Buffer.isBuffer(input)) {
  34. input.on('error', reject);
  35. }
  36. extract.on('finish', () => resolve(files));
  37. extract.on('error', reject);
  38. });
  39. extract.then = promise.then.bind(promise);
  40. extract.catch = promise.catch.bind(promise);
  41. if (Buffer.isBuffer(input)) {
  42. extract.end(input);
  43. } else {
  44. input.pipe(extract);
  45. }
  46. return extract;
  47. };