/
NodeFS.js
235 lines (204 loc) Β· 6.11 KB
/
NodeFS.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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// @flow
import type {ReadStream, Stats} from 'fs';
import type {Writable} from 'stream';
import type {FileOptions, FileSystem, Encoding} from './types';
import type {FilePath} from '@parcel/types';
import type {
Event,
Options as WatcherOptions,
AsyncSubscription,
} from '@parcel/watcher';
import fs from 'graceful-fs';
import nativeFS from 'fs';
import ncp from 'ncp';
import {promisify} from 'util';
import {registerSerializableClass} from '@parcel/core';
import {hashStream} from '@parcel/utils';
import watcher from '@parcel/watcher';
import packageJSON from '../package.json';
import * as searchNative from '@parcel/fs-search';
import * as searchJS from './find';
// Most of this can go away once we only support Node 10+, which includes
// require('fs').promises
const realpath = promisify(
process.platform === 'win32' ? fs.realpath : fs.realpath.native,
);
const isPnP = process.versions.pnp != null;
export class NodeFS implements FileSystem {
readFile: any = promisify(fs.readFile);
copyFile: any = promisify(fs.copyFile);
stat: any = promisify(fs.stat);
readdir: any = promisify(fs.readdir);
unlink: any = promisify(fs.unlink);
utimes: any = promisify(fs.utimes);
ncp: any = promisify(ncp);
createReadStream: (path: string, options?: any) => ReadStream =
fs.createReadStream;
cwd: () => string = () => process.cwd();
chdir: (directory: string) => void = directory => process.chdir(directory);
statSync: (path: string) => Stats = path => fs.statSync(path);
realpathSync: (path: string, cache?: any) => string =
process.platform === 'win32' ? fs.realpathSync : fs.realpathSync.native;
existsSync: (path: string) => boolean = fs.existsSync;
readdirSync: any = (fs.readdirSync: any);
findAncestorFile: any = isPnP
? (...args) => searchJS.findAncestorFile(this, ...args)
: searchNative.findAncestorFile;
findNodeModule: any = isPnP
? (...args) => searchJS.findNodeModule(this, ...args)
: searchNative.findNodeModule;
findFirstFile: any = isPnP
? (...args) => searchJS.findFirstFile(this, ...args)
: searchNative.findFirstFile;
createWriteStream(filePath: string, options: any): Writable {
// Make createWriteStream atomic
let tmpFilePath = getTempFilePath(filePath);
let failed = false;
const move = async () => {
if (!failed) {
try {
await fs.promises.rename(tmpFilePath, filePath);
} catch (e) {
// This is adapted from fs-write-stream-atomic. Apparently
// Windows doesn't like renaming when the target already exists.
if (
process.platform === 'win32' &&
e.syscall &&
e.syscall === 'rename' &&
e.code &&
e.code === 'EPERM'
) {
let [hashTmp, hashTarget] = await Promise.all([
hashStream(writeStream.__atomicTmp),
hashStream(writeStream.__atomicTarget),
]);
await this.unlink(writeStream.__atomicTmp);
if (hashTmp != hashTarget) {
throw e;
}
}
}
}
};
let writeStream = fs.createWriteStream(tmpFilePath, {
...options,
fs: {
...fs,
close: (fd, cb) => {
fs.close(fd, err => {
if (err) {
cb(err);
} else {
move().then(
() => cb(),
err => cb(err),
);
}
});
},
},
});
writeStream.once('error', () => {
failed = true;
fs.unlinkSync(tmpFilePath);
});
return writeStream;
}
async writeFile(
filePath: FilePath,
contents: Buffer | string,
options: ?FileOptions,
): Promise<void> {
let tmpFilePath = getTempFilePath(filePath);
await fs.promises.writeFile(tmpFilePath, contents, options);
await fs.promises.rename(tmpFilePath, filePath);
}
readFileSync(filePath: FilePath, encoding?: Encoding): any {
if (encoding != null) {
return fs.readFileSync(filePath, encoding);
}
return fs.readFileSync(filePath);
}
async realpath(originalPath: string): Promise<string> {
try {
return await realpath(originalPath, 'utf8');
} catch (e) {
// do nothing
}
return originalPath;
}
exists(filePath: FilePath): Promise<boolean> {
return new Promise(resolve => {
fs.exists(filePath, resolve);
});
}
watch(
dir: FilePath,
fn: (err: ?Error, events: Array<Event>) => mixed,
opts: WatcherOptions,
): Promise<AsyncSubscription> {
return watcher.subscribe(dir, fn, opts);
}
getEventsSince(
dir: FilePath,
snapshot: FilePath,
opts: WatcherOptions,
): Promise<Array<Event>> {
return watcher.getEventsSince(dir, snapshot, opts);
}
async writeSnapshot(
dir: FilePath,
snapshot: FilePath,
opts: WatcherOptions,
): Promise<void> {
await watcher.writeSnapshot(dir, snapshot, opts);
}
static deserialize(): NodeFS {
return new NodeFS();
}
serialize(): null {
return null;
}
async mkdirp(filePath: FilePath): Promise<void> {
await nativeFS.promises.mkdir(filePath, {recursive: true});
}
async rimraf(filePath: FilePath): Promise<void> {
if (fs.promises.rm) {
await fs.promises.rm(filePath, {recursive: true, force: true});
return;
}
// fs.promises.rm is not supported in node 12...
let stat;
try {
stat = await this.stat(filePath);
} catch (err) {
return;
}
if (stat.isDirectory()) {
// $FlowFixMe
await nativeFS.promises.rmdir(filePath, {recursive: true});
} else {
await nativeFS.promises.unlink(filePath);
}
}
}
registerSerializableClass(`${packageJSON.version}:NodeFS`, NodeFS);
let writeStreamCalls = 0;
let threadId;
try {
({threadId} = require('worker_threads'));
} catch {
//
}
// Generate a temporary file path used for atomic writing of files.
function getTempFilePath(filePath: FilePath) {
writeStreamCalls = writeStreamCalls % Number.MAX_SAFE_INTEGER;
return (
filePath +
'.' +
process.pid +
(threadId != null ? '.' + threadId : '') +
'.' +
(writeStreamCalls++).toString(36)
);
}