Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/css-language-features/client/src/node/nodeFs.ts
3322 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as fs from 'fs';
7
import { Uri } from 'vscode';
8
import { RequestService, FileType } from '../requests';
9
10
export function getNodeFSRequestService(): RequestService {
11
function ensureFileUri(location: string) {
12
if (!location.startsWith('file://')) {
13
throw new Error('fileRequestService can only handle file URLs');
14
}
15
}
16
return {
17
getContent(location: string, encoding?: BufferEncoding) {
18
ensureFileUri(location);
19
return new Promise((c, e) => {
20
const uri = Uri.parse(location);
21
fs.readFile(uri.fsPath, encoding, (err, buf) => {
22
if (err) {
23
return e(err);
24
}
25
c(buf.toString());
26
27
});
28
});
29
},
30
stat(location: string) {
31
ensureFileUri(location);
32
return new Promise((c, e) => {
33
const uri = Uri.parse(location);
34
fs.stat(uri.fsPath, (err, stats) => {
35
if (err) {
36
if (err.code === 'ENOENT') {
37
return c({ type: FileType.Unknown, ctime: -1, mtime: -1, size: -1 });
38
} else {
39
return e(err);
40
}
41
}
42
43
let type = FileType.Unknown;
44
if (stats.isFile()) {
45
type = FileType.File;
46
} else if (stats.isDirectory()) {
47
type = FileType.Directory;
48
} else if (stats.isSymbolicLink()) {
49
type = FileType.SymbolicLink;
50
}
51
52
c({
53
type,
54
ctime: stats.ctime.getTime(),
55
mtime: stats.mtime.getTime(),
56
size: stats.size
57
});
58
});
59
});
60
},
61
readDirectory(location: string) {
62
ensureFileUri(location);
63
return new Promise((c, e) => {
64
const path = Uri.parse(location).fsPath;
65
66
fs.readdir(path, { withFileTypes: true }, (err, children) => {
67
if (err) {
68
return e(err);
69
}
70
c(children.map(stat => {
71
if (stat.isSymbolicLink()) {
72
return [stat.name, FileType.SymbolicLink];
73
} else if (stat.isDirectory()) {
74
return [stat.name, FileType.Directory];
75
} else if (stat.isFile()) {
76
return [stat.name, FileType.File];
77
} else {
78
return [stat.name, FileType.Unknown];
79
}
80
}));
81
});
82
});
83
}
84
};
85
}
86
87