Skip to content

Commit c541155

Browse files
committed
fs: move rmSync implementation to c++
1 parent 895fcb0 commit c541155

File tree

6 files changed

+96
-152
lines changed

6 files changed

+96
-152
lines changed

lib/fs.js

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,6 @@ let promises = null;
159159
let ReadStream;
160160
let WriteStream;
161161
let rimraf;
162-
let rimrafSync;
163162
let kResistStopPropagation;
164163

165164
// These have to be separate because of how graceful-fs happens to do it's
@@ -1126,7 +1125,7 @@ function lazyLoadCp() {
11261125

11271126
function lazyLoadRimraf() {
11281127
if (rimraf === undefined)
1129-
({ rimraf, rimrafSync } = require('internal/fs/rimraf'));
1128+
({ rimraf } = require('internal/fs/rimraf'));
11301129
}
11311130

11321131
/**
@@ -1194,8 +1193,7 @@ function rmdirSync(path, options) {
11941193
emitRecursiveRmdirWarning();
11951194
options = validateRmOptionsSync(path, { ...options, force: false }, true);
11961195
if (options !== false) {
1197-
lazyLoadRimraf();
1198-
return rimrafSync(path, options);
1196+
return binding.rmSync(path, options.maxRetries, options.recursive, options.retryDelay);
11991197
}
12001198
} else {
12011199
validateRmdirOptions(options);
@@ -1246,11 +1244,8 @@ function rm(path, options, callback) {
12461244
* @returns {void}
12471245
*/
12481246
function rmSync(path, options) {
1249-
lazyLoadRimraf();
1250-
return rimrafSync(
1251-
getValidatedPath(path),
1252-
validateRmOptionsSync(path, options, false),
1253-
);
1247+
const opts = validateRmOptionsSync(path, options, false);
1248+
return binding.rmSync(getValidatedPath(path), opts.maxRetries, opts.recursive, opts.retryDelay);
12541249
}
12551250

12561251
/**

lib/internal/fs/rimraf.js

Lines changed: 1 addition & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -16,27 +16,19 @@ const { Buffer } = require('buffer');
1616
const fs = require('fs');
1717
const {
1818
chmod,
19-
chmodSync,
2019
lstat,
21-
lstatSync,
2220
readdir,
23-
readdirSync,
2421
rmdir,
25-
rmdirSync,
2622
stat,
27-
statSync,
2823
unlink,
29-
unlinkSync,
3024
} = fs;
3125
const { sep } = require('path');
3226
const { setTimeout } = require('timers');
33-
const { sleep } = require('internal/util');
3427
const notEmptyErrorCodes = new SafeSet(['ENOTEMPTY', 'EEXIST', 'EPERM']);
3528
const retryErrorCodes = new SafeSet(
3629
['EBUSY', 'EMFILE', 'ENFILE', 'ENOTEMPTY', 'EPERM']);
3730
const isWindows = process.platform === 'win32';
3831
const epermHandler = isWindows ? fixWinEPERM : _rmdir;
39-
const epermHandlerSync = isWindows ? fixWinEPERMSync : _rmdirSync;
4032
const readdirEncoding = 'buffer';
4133
const separator = Buffer.from(sep);
4234

@@ -173,138 +165,4 @@ function rimrafPromises(path, options) {
173165
}
174166

175167

176-
function rimrafSync(path, options) {
177-
let stats;
178-
179-
try {
180-
stats = lstatSync(path);
181-
} catch (err) {
182-
if (err.code === 'ENOENT')
183-
return;
184-
185-
// Windows can EPERM on stat.
186-
if (isWindows && err.code === 'EPERM')
187-
fixWinEPERMSync(path, options, err);
188-
}
189-
190-
try {
191-
// SunOS lets the root user unlink directories.
192-
if (stats?.isDirectory())
193-
_rmdirSync(path, options, null);
194-
else
195-
_unlinkSync(path, options);
196-
} catch (err) {
197-
if (err.code === 'ENOENT')
198-
return;
199-
if (err.code === 'EPERM')
200-
return epermHandlerSync(path, options, err);
201-
if (err.code !== 'EISDIR')
202-
throw err;
203-
204-
_rmdirSync(path, options, err);
205-
}
206-
}
207-
208-
209-
function _unlinkSync(path, options) {
210-
const tries = options.maxRetries + 1;
211-
212-
for (let i = 1; i <= tries; i++) {
213-
try {
214-
return unlinkSync(path);
215-
} catch (err) {
216-
// Only sleep if this is not the last try, and the delay is greater
217-
// than zero, and an error was encountered that warrants a retry.
218-
if (retryErrorCodes.has(err.code) &&
219-
i < tries &&
220-
options.retryDelay > 0) {
221-
sleep(i * options.retryDelay);
222-
} else if (err.code === 'ENOENT') {
223-
// The file is already gone.
224-
return;
225-
} else if (i === tries) {
226-
throw err;
227-
}
228-
}
229-
}
230-
}
231-
232-
233-
function _rmdirSync(path, options, originalErr) {
234-
try {
235-
rmdirSync(path);
236-
} catch (err) {
237-
if (err.code === 'ENOENT')
238-
return;
239-
if (err.code === 'ENOTDIR') {
240-
throw originalErr || err;
241-
}
242-
243-
if (notEmptyErrorCodes.has(err.code)) {
244-
// Removing failed. Try removing all children and then retrying the
245-
// original removal. Windows has a habit of not closing handles promptly
246-
// when files are deleted, resulting in spurious ENOTEMPTY failures. Work
247-
// around that issue by retrying on Windows.
248-
const pathBuf = Buffer.from(path);
249-
250-
ArrayPrototypeForEach(readdirSync(pathBuf, readdirEncoding), (child) => {
251-
const childPath = Buffer.concat([pathBuf, separator, child]);
252-
253-
rimrafSync(childPath, options);
254-
});
255-
256-
const tries = options.maxRetries + 1;
257-
258-
for (let i = 1; i <= tries; i++) {
259-
try {
260-
return fs.rmdirSync(path);
261-
} catch (err) {
262-
// Only sleep if this is not the last try, and the delay is greater
263-
// than zero, and an error was encountered that warrants a retry.
264-
if (retryErrorCodes.has(err.code) &&
265-
i < tries &&
266-
options.retryDelay > 0) {
267-
sleep(i * options.retryDelay);
268-
} else if (err.code === 'ENOENT') {
269-
// The file is already gone.
270-
return;
271-
} else if (i === tries) {
272-
throw err;
273-
}
274-
}
275-
}
276-
}
277-
278-
throw originalErr || err;
279-
}
280-
}
281-
282-
283-
function fixWinEPERMSync(path, options, originalErr) {
284-
try {
285-
chmodSync(path, 0o666);
286-
} catch (err) {
287-
if (err.code === 'ENOENT')
288-
return;
289-
290-
throw originalErr;
291-
}
292-
293-
let stats;
294-
295-
try {
296-
stats = statSync(path, { throwIfNoEntry: false });
297-
} catch {
298-
throw originalErr;
299-
}
300-
301-
if (stats === undefined) return;
302-
303-
if (stats.isDirectory())
304-
_rmdirSync(path, options, originalErr);
305-
else
306-
_unlinkSync(path, options);
307-
}
308-
309-
310-
module.exports = { rimraf, rimrafPromises, rimrafSync };
168+
module.exports = { rimraf, rimrafPromises };

src/node_errors.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ void OOMErrorHandler(const char* location, const v8::OOMDetails& details);
7070
V(ERR_DLOPEN_FAILED, Error) \
7171
V(ERR_ENCODING_INVALID_ENCODED_DATA, TypeError) \
7272
V(ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE, Error) \
73+
V(ERR_FS_EISDIR, Error) \
7374
V(ERR_ILLEGAL_CONSTRUCTOR, Error) \
7475
V(ERR_INVALID_ADDRESS, Error) \
7576
V(ERR_INVALID_ARG_VALUE, TypeError) \

src/node_file.cc

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@
4848
# include <io.h>
4949
#endif
5050

51+
#include <unistd.h>
52+
5153
namespace node {
5254

5355
namespace fs {
@@ -1605,6 +1607,88 @@ static void RMDir(const FunctionCallbackInfo<Value>& args) {
16051607
}
16061608
}
16071609

1610+
static void RmSync(const FunctionCallbackInfo<Value>& args) {
1611+
Environment* env = Environment::GetCurrent(args);
1612+
Isolate* isolate = env->isolate();
1613+
1614+
CHECK_EQ(args.Length(), 4); // path, maxRetries, recursive, retryDelay
1615+
1616+
BufferValue path(isolate, args[0]);
1617+
CHECK_NOT_NULL(*path);
1618+
ToNamespacedPath(env, &path);
1619+
THROW_IF_INSUFFICIENT_PERMISSIONS(
1620+
env, permission::PermissionScope::kFileSystemWrite, path.ToStringView());
1621+
auto file_path = std::filesystem::path(path.ToStringView());
1622+
std::error_code error;
1623+
auto file_status = std::filesystem::status(file_path, error);
1624+
1625+
if (file_status.type() == std::filesystem::file_type::not_found) {
1626+
return;
1627+
}
1628+
1629+
int maxRetries = args[1].As<Int32>()->Value();
1630+
int recursive = args[2]->IsTrue();
1631+
int retryDelay = args[3].As<Int32>()->Value();
1632+
1633+
// File is a directory and recursive is false
1634+
if (file_status.type() == std::filesystem::file_type::directory &&
1635+
!recursive) {
1636+
return THROW_ERR_FS_EISDIR(
1637+
isolate, "Path is a directory: %s", file_path.c_str());
1638+
}
1639+
1640+
// Allowed errors are:
1641+
// - EBUSY: std::errc::device_or_resource_busy
1642+
// - EMFILE: std::errc::too_many_files_open
1643+
// - ENFILE: std::errc::too_many_files_open_in_system
1644+
// - ENOTEMPTY: std::errc::directory_not_empty
1645+
// - EPERM: std::errc::operation_not_permitted
1646+
auto can_omit_error = [](std::error_code error) -> bool {
1647+
return (error == std::errc::device_or_resource_busy ||
1648+
error == std::errc::too_many_files_open ||
1649+
error == std::errc::too_many_files_open_in_system ||
1650+
error == std::errc::directory_not_empty ||
1651+
error == std::errc::operation_not_permitted);
1652+
};
1653+
1654+
while (maxRetries >= 0) {
1655+
if (recursive) {
1656+
std::filesystem::remove_all(file_path, error);
1657+
} else {
1658+
std::filesystem::remove(file_path, error);
1659+
}
1660+
1661+
if (!error || error == std::errc::no_such_file_or_directory) {
1662+
return;
1663+
} else if (!can_omit_error(error)) {
1664+
break;
1665+
}
1666+
1667+
if (retryDelay != 0) {
1668+
sleep(retryDelay / 1000);
1669+
}
1670+
maxRetries--;
1671+
}
1672+
1673+
if (error == std::errc::operation_not_permitted) {
1674+
std::string message = "Operation not permitted: " + file_path.string();
1675+
return env->ThrowErrnoException(
1676+
EPERM, "rm", message.c_str(), file_path.c_str());
1677+
} else if (error == std::errc::directory_not_empty) {
1678+
std::string message = "Directory not empty: " + file_path.string();
1679+
return env->ThrowErrnoException(
1680+
EACCES, "rm", message.c_str(), file_path.c_str());
1681+
} else if (error == std::errc::not_a_directory) {
1682+
std::string message = "Not a directory: " + file_path.string();
1683+
return env->ThrowErrnoException(
1684+
ENOTDIR, "rm", message.c_str(), file_path.c_str());
1685+
}
1686+
1687+
std::string message = "Unknown error: " + error.message();
1688+
return env->ThrowErrnoException(
1689+
UV_UNKNOWN, "rm", message.c_str(), file_path.c_str());
1690+
}
1691+
16081692
int MKDirpSync(uv_loop_t* loop,
16091693
uv_fs_t* req,
16101694
const std::string& path,
@@ -3323,6 +3407,7 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
33233407
SetMethod(isolate, target, "rename", Rename);
33243408
SetMethod(isolate, target, "ftruncate", FTruncate);
33253409
SetMethod(isolate, target, "rmdir", RMDir);
3410+
SetMethod(isolate, target, "rmSync", RmSync);
33263411
SetMethod(isolate, target, "mkdir", MKDir);
33273412
SetMethod(isolate, target, "readdir", ReadDir);
33283413
SetFastMethod(isolate,
@@ -3447,6 +3532,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
34473532
registry->Register(Rename);
34483533
registry->Register(FTruncate);
34493534
registry->Register(RMDir);
3535+
registry->Register(RmSync);
34503536
registry->Register(MKDir);
34513537
registry->Register(ReadDir);
34523538
registry->Register(InternalModuleStat);

test/parallel/test-fs-rm.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,7 @@ if (isGitPresent) {
541541
name: 'Error',
542542
});
543543
} catch (err) {
544+
console.log(err);
544545
// Only fail the test if the folder was not deleted.
545546
// as in some cases rmSync successfully deletes read-only folders.
546547
if (fs.existsSync(root)) {

typings/internalBinding/fs.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,8 @@ declare namespace InternalFSBinding {
194194
function rmdir(path: string): void;
195195
function rmdir(path: string, usePromises: typeof kUsePromises): Promise<void>;
196196

197+
function rmSync(path: StringOrBuffer, maxRetries: number, recursive: boolean, retryDelay: number): void;
198+
197199
function stat(path: StringOrBuffer, useBigint: boolean, req: FSReqCallback<Float64Array | BigUint64Array>): void;
198200
function stat(path: StringOrBuffer, useBigint: true, req: FSReqCallback<BigUint64Array>): void;
199201
function stat(path: StringOrBuffer, useBigint: false, req: FSReqCallback<Float64Array>): void;
@@ -276,6 +278,7 @@ export interface FsBinding {
276278
realpath: typeof InternalFSBinding.realpath;
277279
rename: typeof InternalFSBinding.rename;
278280
rmdir: typeof InternalFSBinding.rmdir;
281+
rmSync: typeof InternalFSBinding.rmSync;
279282
stat: typeof InternalFSBinding.stat;
280283
symlink: typeof InternalFSBinding.symlink;
281284
unlink: typeof InternalFSBinding.unlink;

0 commit comments

Comments
 (0)