Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mololab
GitHub Repository: mololab/json-translator
Path: blob/master/src/core/core.ts
235 views
1
import * as fs from 'fs/promises';
2
import * as YAML from 'yaml';
3
import { matchYamlExt } from '../utils/yaml';
4
import { error, messages } from '../utils/console';
5
6
export async function checkFile(objectPath: string):Promise<boolean> {
7
try {
8
await fs.access(objectPath);
9
return Promise.resolve(true)
10
} catch {
11
return Promise.resolve(false)
12
}
13
}
14
15
export async function getFile(objectPath: string) {
16
let json_file: any = undefined;
17
18
await fs
19
.readFile(objectPath, 'utf8')
20
.then(data => {
21
// This function should return a string with JSON-encoded data.
22
// To preserve the contract, YAML files should be parsed to object
23
// and then stringified to JSON string.
24
json_file = matchYamlExt(objectPath)
25
? JSON.stringify(YAML.parse(data))
26
: data;
27
})
28
.catch(_ => {
29
json_file = undefined;
30
});
31
32
return json_file;
33
}
34
35
export function getRootFolder(path: string) {
36
let arr = path.split('/');
37
arr.pop();
38
39
let root = arr.join('/');
40
41
if (root === undefined || root === '') {
42
root = './';
43
}
44
45
return root;
46
}
47
48
export async function saveFilePublic(path: string, data: any) {
49
// When path extension is for YAML file, then stringify with YAML encoder.
50
// Otherwise, default JSON encoder is used.
51
var json = matchYamlExt(path) ? YAML.stringify(data) : JSON.stringify(data);
52
53
await fs
54
.writeFile(path, json, 'utf8')
55
.then(_ => {})
56
.catch(_ => {
57
error(messages.file.cannot_save_file);
58
});
59
}
60
61