filesystem.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import * as fs from "fs";
  2. /**
  3. * Typing for the fields of package.json we care about
  4. */
  5. export interface PackageJson {
  6. [key: string]: string;
  7. }
  8. /**
  9. * A function that json from a file
  10. */
  11. export interface ReadJsonSync {
  12. // tslint:disable-next-line:no-any
  13. (packageJsonPath: string): any | undefined;
  14. }
  15. export interface FileExistsSync {
  16. (name: string): boolean;
  17. }
  18. export interface FileExistsAsync {
  19. (path: string, callback: (err?: Error, exists?: boolean) => void): void;
  20. }
  21. export interface ReadJsonAsyncCallback {
  22. // tslint:disable-next-line:no-any
  23. (err?: Error, content?: any): void;
  24. }
  25. export interface ReadJsonAsync {
  26. (path: string, callback: ReadJsonAsyncCallback): void;
  27. }
  28. export function fileExistsSync(path: string): boolean {
  29. try {
  30. const stats = fs.statSync(path);
  31. return stats.isFile();
  32. } catch (err) {
  33. // If error, assume file did not exist
  34. return false;
  35. }
  36. }
  37. /**
  38. * Reads package.json from disk
  39. * @param file Path to package.json
  40. */
  41. // tslint:disable-next-line:no-any
  42. export function readJsonFromDiskSync(packageJsonPath: string): any | undefined {
  43. if (!fs.existsSync(packageJsonPath)) {
  44. return undefined;
  45. }
  46. return require(packageJsonPath);
  47. }
  48. export function readJsonFromDiskAsync(
  49. path: string,
  50. // tslint:disable-next-line:no-any
  51. callback: (err?: Error, content?: any) => void
  52. ): void {
  53. fs.readFile(path, "utf8", (err, result) => {
  54. // If error, assume file did not exist
  55. if (err || !result) {
  56. return callback();
  57. }
  58. const json = JSON.parse(result);
  59. return callback(undefined, json);
  60. });
  61. }
  62. export function fileExistsAsync(
  63. path2: string,
  64. callback2: (err?: Error, exists?: boolean) => void
  65. ): void {
  66. fs.stat(path2, (err: Error, stats: fs.Stats) => {
  67. if (err) {
  68. // If error assume file does not exist
  69. return callback2(undefined, false);
  70. }
  71. callback2(undefined, stats ? stats.isFile() : false);
  72. });
  73. }
  74. export function removeExtension(path: string): string {
  75. return path.substring(0, path.lastIndexOf(".")) || path;
  76. }