microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
a31b007c2af965bbb579b8e9ae0054a403891c95

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/utils/node/fileSystem.ts

68lines · 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 Q from "q";
6
7export class FileSystem {
8
9 public ensureDirectory(dir: string): Q.Promise<void> {
10 return Q.nfcall(fs.stat, dir).then((stat: fs.Stats): void => {
11 if (stat.isDirectory()) {
12 return;
13 } else {
14 throw new Error(`Expected ${dir} to be a directory`);
15 }
16 }, (err: Error & {code?: string}): Q.Promise<any> => {
17 if (err && err.code === "ENOENT") {
18 return Q.nfcall(fs.mkdir, dir);
19 } else {
20 throw err;
21 }
22 });
23 }
24
25 public ensureFileWithContents(file: string, contents: string): Q.Promise<void> {
26 return Q.nfcall(fs.stat, file).then((stat: fs.Stats): void => {
27 if (!stat.isFile()) {
28 throw new Error(`Expected ${file} to be a file`);
29 }
30 // The file already exists, assume the contents are good and do not touch it.
31 }, (err: Error & {code?: string}): Q.Promise<any> => {
32 if (err && err.code === "ENOENT") {
33 return Q.nfcall(fs.writeFile, file, contents);
34 } else {
35 throw err;
36 }
37 });
38 }
39
40 public fileExistsSync(filename: string) {
41 try {
42 fs.lstatSync(filename);
43 return true;
44 } catch (error) {
45 return false;
46 }
47 }
48
49 public deleteFileIfExistsSync(filename: string) {
50 if (this.fileExistsSync(filename)) {
51 fs.unlinkSync(filename);
52 }
53 }
54
55 public readFile(filename: string, encoding: string): Q.Promise<string> {
56 let contents = Q.defer<string>();
57
58 fs.readFile(filename, encoding, (err: NodeJS.ErrnoException, data: string) => {
59 if (err) {
60 contents.reject(err);
61 } else {
62 contents.resolve(data);
63 }
64 });
65
66 return contents.promise;
67 }
68}
69