-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfiles.ts
More file actions
111 lines (99 loc) · 2.57 KB
/
Copy pathfiles.ts
File metadata and controls
111 lines (99 loc) · 2.57 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import axios from "axios";
import FormData from "form-data";
import { ClientError } from "../types/client-error";
import { IEntry, IStat } from "../types/types";
export class Files {
private url: string;
constructor(url: string) {
this.url = url;
}
/**
Write to a file in MFS.
*/
public async write(params: {
content: any;
path: string;
create?: boolean;
parents?: boolean;
rawLeaves?: boolean;
/**
* If true, it will truncate the file before writing to it.
*/
truncate?: boolean;
}): Promise<boolean> {
params.create = params.create || true;
params.parents = params.parents || true;
try {
const form = new FormData();
form.append("file", params.content);
let receivedMessage = "";
const url = new URL(
`${this.url}/files/write?arg=${params.path}&cid-version=1&create=${
params.create
}&parents=${params.parents}${
params.rawLeaves == false ? "&raw-leaves=false" : ""
}${params.truncate == true ? "&truncate=true" : ""}`
);
await new Promise((resolve, reject) => {
form.submit(
{
host: url.hostname,
port: url.port,
path: url.pathname + url.search,
},
(err, res) => {
if (err) {
throw err;
}
res.on("data", (data) => {
receivedMessage += data.toString();
});
res.on("end", () => {
resolve(true);
});
res.on("error", (data) => {
reject(data);
});
}
);
});
if (receivedMessage) {
throw new Error(receivedMessage);
}
return true;
} catch (err) {
throw new ClientError(err);
}
}
/**
* List all entries (files and directories) for path
* @param params
* @returns
*/
public async ls(params: { path?: string }): Promise<IEntry[]> {
try {
const res = await axios.post(
`${this.url}/files/ls?long=1${params.path ? "&arg=" + params.path : ""}`
);
return res.data.Entries;
} catch (err) {
throw new ClientError(err);
}
}
/**
* Get properties of a object in given path
* @param params
* @returns
*/
public async stat(params: { path: string }): Promise<IStat> {
try {
const objectStat = (
await axios.post(`${this.url}/files/stat?arg=${params.path}`)
).data;
console.info(objectStat);
return objectStat;
} catch (err) {
throw new ClientError(err);
}
}
}