microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
3806187c0fbdfb47dd51f50f84fe4ef7642eef3d

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/utils/node/fileSystem.ts

77lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as fs from "fs";
5import * as path from "path";
6import * as Q from "q";
7
8export class FileSystem {
9
10 public ensureDirectory(dir: string): Q.Promise<void> {
11 return Q.nfcall(fs.stat, dir).then((stat: fs.Stats): void => {
12 if (stat.isDirectory()) {
13 return;
14 } else {
15 throw new Error(`Expected ${dir} to be a directory`);
16 }
17 }, (err: Error & {code?: string}): Q.Promise<any> => {
18 if (err && err.code === "ENOENT") {
19 return Q.nfcall(fs.mkdir, dir);
20 } else {
21 throw err;
22 }
23 });
24 }
25
26 public ensureFileWithContents(file: string, contents: string): Q.Promise<void> {
27 return Q.nfcall(fs.stat, file).then((stat: fs.Stats): void => {
28 if (!stat.isFile()) {
29 throw new Error(`Expected ${file} to be a file`);
30 }
31 // The file already exists, assume the contents are good and do not touch it.
32 }, (err: Error & {code?: string}): Q.Promise<any> => {
33 if (err && err.code === "ENOENT") {
34 return Q.nfcall(fs.writeFile, file, contents);
35 } else {
36 throw err;
37 }
38 });
39 }
40
41 public fileExistsSync(filename: string) {
42 try {
43 fs.lstatSync(filename);
44 return true;
45 } catch (error) {
46 return false;
47 }
48 }
49
50 public deleteFileIfExistsSync(filename: string) {
51 if (this.fileExistsSync(filename)) {
52 fs.unlinkSync(filename);
53 }
54 }
55
56 public readFile(filename: string, encoding: string = "utf8"): Q.Promise<string> {
57 throw new Error("To implement with Q.denodeify");
58 }
59
60 public writeFile(filename: string, data: any): Q.Promise<void> {
61 throw new Error("To implement with Q.denodeify");
62 }
63
64 public findFilesByExtension(folder: string, extension: string): Q.Promise<string[]> {
65 return Q.nfcall(fs.readdir, folder).then((files: string[]) => {
66 const extFiles = files.filter((file: string) => path.extname(file) === `.${extension}`);
67 if (extFiles.length === 0) {
68 throw new Error(`Unable to find any ${extension} files.`);
69 }
70 return extFiles;
71 });
72 }
73}
74
75// We only copy these two methods, instead of all the methods of fs, because we need to remember to add the signatures manually
76// to class FileSystem with a throw new Error("To implement with Q.denodeify"); implementation before adding it here
77["writeFile", "readFile"].forEach(methodName => (<any>FileSystem.prototype)[methodName] = Q.denodeify((<any>fs)[methodName]));
78