microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/utils/fileSystemUtil.ts
39lines · 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 | |
| 4 | import * as fs from "fs"; |
| 5 | import * as Q from "q"; |
| 6 | |
| 7 | export class FileSystemUtil { |
| 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 | } |