forked from GoogleChromeLabs/ndb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_system_io.js
75 lines (67 loc) · 1.66 KB
/
file_system_io.js
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
const { rpc, rpc_process } = require('carlo/rpc');
const fs = require('fs');
const { URL } = require('url');
class FileSystemIO {
constructor() {
require('../lib/process_utility.js')('file_system_io', () => this.dispose());
}
/**
* @param {string} fileURL
* @param {string} encoding
*/
readFile(fileURL, encoding) {
return fs.readFileSync(new URL(fileURL), encoding);
}
/**
* @param {string} fileURL
* @param {string} content
* @param {string} encoding
*/
writeFile(fileURL, content, encoding) {
if (encoding === 'base64')
content = Buffer.from(content, 'base64');
fs.writeFileSync(new URL(fileURL), content, {encoding: encoding});
}
/**
* @param {string} folderURL
*/
createFile(folderURL) {
let name = 'NewFile';
let counter = 1;
while (fs.existsSync(new URL(folderURL + '/' + name))) {
name = 'NewFile' + counter;
++counter;
}
fs.writeFileSync(new URL(folderURL + '/' + name), '');
return folderURL + '/' + name;
}
/**
* @param {string} fileURL
*/
deleteFile(fileURL) {
try {
fs.unlinkSync(new URL(fileURL));
return true;
} catch (e) {
return false;
}
}
/**
* @param {string} fileURL
* @param {string} newName
*/
renameFile(fileURL, newName) {
const newURL = new URL(fileURL.substr(0, fileURL.lastIndexOf('/') + 1) + newName);
try {
if (fs.existsSync(newURL)) return false;
fs.renameSync(new URL(fileURL), newURL);
return true;
} catch (e) {
return false;
}
}
dispose() {
Promise.resolve().then(() => process.exit(0));
}
}
rpc_process.init(args => rpc.handle(new FileSystemIO()));