All files data-acquisition.ts

89.66% Statements 26/29
55.56% Branches 5/9
87.5% Functions 7/8
92.31% Lines 24/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 622x 2x       5x     5x         7x             2x 7x 7x   5x 5x 14x 5x 5x     5x     5x   5x       5x     2x 5x 5x 3x   2x             2x         2x  
import * as getUri from "get-uri";
import { toRawDataUrl } from "./uri-manipulation";
import { Readable } from "stream";
 
function stripBom(text: string): string {
  Iif (text.charCodeAt(0) === 0xfeff) {
    return text.slice(1);
  }
  return text;
}
 
function getUriAsync(uri: string, options: { headers: { [key: string]: string } }): Promise<Readable> {
  // headers being passed is not described in the typing but does works.
  return getUri(uri, options as getUri.GetUriOptions);
}
 
/**
 * Loads a UTF8 string from given URI.
 * @uri to load. Can be a remote url or a local file path(using file: protocol).
 */
export async function readUri(uri: string, headers: { [key: string]: string } = {}): Promise<string> {
  const actualUri = toRawDataUrl(uri);
  const readable = await getUriAsync(actualUri, { headers: headers });
 
  const readAll = new Promise<Buffer>(function (resolve, reject) {
    let result = Buffer.alloc(0);
    readable.on("data", (data) => (result = Buffer.concat([result, data])));
    readable.on("end", () => resolve(result));
    readable.on("error", (err) => reject(err));
  });
 
  const result = await readAll;
 
  // make sure we can read 4 bytes into the file before trying to fix it!
  Eif (result.length > 3) {
    // fix up UTF16le files
    Iif (result.readUInt16LE(0) === 65533 && result.readUInt16LE(1) === 65533) {
      return stripBom(result.slice(2).toString("utf16le"));
    }
  }
  return stripBom(result.toString("utf8"));
}
 
export async function existsUri(uri: string): Promise<boolean> {
  try {
    await readUri(uri);
    return true;
  } catch (e) {
    return false;
  }
}
 
/**
 * @deprecated use readUri instead
 */
export const ReadUri = readUri;
 
/**
 * @deprecated use existsUri instead
 */
export const ExistsUri = existsUri;