helpers.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import * as util from 'util';
  7. import * as fs from 'fs';
  8. import fetch from 'node-fetch';
  9. require('util.promisify').shim();
  10. import { CIF } from '../../mol-io/reader/cif';
  11. import { Progress } from '../../mol-task';
  12. const readFileAsync = util.promisify(fs.readFile);
  13. async function readFile(path: string) {
  14. if (path.match(/\.bcif$/)) {
  15. const input = await readFileAsync(path);
  16. const data = new Uint8Array(input.byteLength);
  17. for (let i = 0; i < input.byteLength; i++) data[i] = input[i];
  18. return data;
  19. } else {
  20. return readFileAsync(path, 'utf8');
  21. }
  22. }
  23. async function parseCif(data: string|Uint8Array) {
  24. const comp = CIF.parse(data);
  25. const parsed = await comp.run(p => console.log(Progress.format(p)), 250);
  26. if (parsed.isError) throw parsed;
  27. return parsed.result;
  28. }
  29. export async function openCif(path: string) {
  30. const data = await readFile(path);
  31. return parseCif(data);
  32. }
  33. export async function downloadCif(url: string, isBinary: boolean) {
  34. const data = await fetch(url);
  35. return parseCif(isBinary ? new Uint8Array(await data.arrayBuffer()) : await data.text());
  36. }