file-system-utility.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. /**
  4. * @license
  5. * Copyright Google Inc. All Rights Reserved.
  6. *
  7. * Use of this source code is governed by an MIT-style license that can be
  8. * found in the LICENSE file at https://angular.io/license
  9. */
  10. const core_1 = require("@angular-devkit/core");
  11. const fs_1 = require("fs");
  12. /**
  13. * Read a file and returns its content. This supports different file encoding.
  14. */
  15. function readFile(fileName) {
  16. if (!fs_1.existsSync(fileName)) {
  17. throw new core_1.FileDoesNotExistException(fileName);
  18. }
  19. const buffer = fs_1.readFileSync(fileName);
  20. let len = buffer.length;
  21. if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
  22. // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
  23. // flip all byte pairs and treat as little endian.
  24. len &= ~1;
  25. for (let i = 0; i < len; i += 2) {
  26. const temp = buffer[i];
  27. buffer[i] = buffer[i + 1];
  28. buffer[i + 1] = temp;
  29. }
  30. return buffer.toString('utf16le', 2);
  31. }
  32. if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
  33. // Little endian UTF-16 byte order mark detected
  34. return buffer.toString('utf16le', 2);
  35. }
  36. if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
  37. // UTF-8 byte order mark detected
  38. return buffer.toString('utf8', 3);
  39. }
  40. // Default is UTF-8 with no byte order mark
  41. return buffer.toString('utf8');
  42. }
  43. exports.readFile = readFile;
  44. function readJsonFile(path) {
  45. return core_1.parseJson(readFile(path), core_1.JsonParseMode.Loose);
  46. }
  47. exports.readJsonFile = readJsonFile;