file-info.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. /** A File or Blob object or a URL string */
  7. export type FileInput = File | Blob | string
  8. // TODO only support compressed files for which uncompression support is available???
  9. // TODO store globally with decompression plugins?
  10. const compressedExtList = [ 'gz', 'zip' ];
  11. // TODO store globally with parser plugins?
  12. const binaryExtList = [ 'bcif', 'ccp4', 'dcd' ];
  13. export interface FileInfo {
  14. path: string
  15. name: string
  16. ext: string
  17. base: string
  18. dir: string
  19. compressed: string | boolean
  20. binary: boolean
  21. protocol: string
  22. query: string
  23. src: FileInput
  24. }
  25. export function getFileInfo (file: FileInput): FileInfo {
  26. let path: string;
  27. let compressed: string|false;
  28. let protocol = '';
  29. if (file instanceof File) {
  30. path = file.name;
  31. } else if (file instanceof Blob) {
  32. path = '';
  33. } else {
  34. path = file;
  35. }
  36. const queryIndex = path.lastIndexOf('?');
  37. const query = queryIndex !== -1 ? path.substring(queryIndex) : '';
  38. path = path.substring(0, queryIndex === -1 ? path.length : queryIndex);
  39. const name = path.replace(/^.*[\\/]/, '');
  40. let base = name.substring(0, name.lastIndexOf('.'));
  41. const nameSplit = name.split('.');
  42. let ext = nameSplit.length > 1 ? (nameSplit.pop() || '').toLowerCase() : '';
  43. const protocolMatch = path.match(/^(.+):\/\/(.+)$/);
  44. if (protocolMatch) {
  45. protocol = protocolMatch[ 1 ].toLowerCase();
  46. path = protocolMatch[ 2 ] || '';
  47. }
  48. const dir = path.substring(0, path.lastIndexOf('/') + 1);
  49. if (compressedExtList.includes(ext)) {
  50. compressed = ext;
  51. const n = path.length - ext.length - 1;
  52. ext = (path.substr(0, n).split('.').pop() || '').toLowerCase();
  53. const m = base.length - ext.length - 1;
  54. base = base.substr(0, m);
  55. } else {
  56. compressed = false;
  57. }
  58. const binary = binaryExtList.includes(ext);
  59. return { path, name, ext, base, dir, compressed, binary, protocol, query, src: file };
  60. }