This repository has been archived by the owner on Dec 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
file-promise.ts
80 lines (67 loc) · 1.64 KB
/
file-promise.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT
*/
import * as fs from "fs";
import {PromiseBase, TSDNPromise} from "../source/System/Promises/Promise";
import {JsonArray, JsonData, JsonMap} from "../source/JSON";
export module ENCODING
{
export const UTF8:UTF8 = 'utf8';
}
export type UTF8 = 'utf8';
export type Encoding = UTF8;
export type WriteOptions = {
encoding?:string;
mode?:string;
flag?:string;
};
function readFile(path:string, encoding:string = ENCODING.UTF8):TSDNPromise<string>
{
return new TSDNPromise<string>((resolve, reject)=>
{
fs.readFile(
path,
encoding,
(err, data)=>
{
if(err) reject(err);
else resolve(data);
});
});
}
function writeFile(path:string, data:string, options?:WriteOptions):PromiseBase<void>
{
return TSDNPromise.using<void>((resolve, reject)=>
{
fs.writeFile(
path,
data,
options || {},
err=>
{
if(err) reject(err);
else resolve();
});
});
}
export {readFile as read, writeFile as write};
export module json
{
export function read<T extends JsonMap | JsonArray>(
path:string,
encoding?:string):PromiseBase<T>
export function read(path:string, encoding?:string):PromiseBase<JsonData>
export function read<T extends JsonMap | JsonArray>(
path:string,
encoding:string = ENCODING.UTF8):PromiseBase<T>
{
return readFile(path, encoding).then(result=>JSON.parse(result));
}
export function write(path:string, data:JsonData, options?:WriteOptions):PromiseBase<void>
{
return TSDNPromise
.using<string>(resolve=>resolve(JSON.stringify(data, null, 2)))
.thenSynchronous(s=>writeFile(path, s, options));
}
}