mirror of
https://github.com/nodejs/node.git
synced 2026-11-30 11:55:44 -05:00
fs: add rm method
This PR introduces a new method fs.rm that provides the behaviour of rimraf when used with the recursive: true and force: true options. PR-URL: https://github.com/nodejs/node/pull/35494 Reviewed-By: Ben Coe <bencoe@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Ruy Adorno <ruyadorno@github.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Michael Dawson <midawson@redhat.com>
This commit is contained in:
1 parent
6141ca318a
commit
4e9f3cc6fe
10 files changed
+518
-37
No files matched your search
@@ -1048,6 +1048,11 @@ added: v14.0.0
|
||||
Used when a feature that is not available
|
||||
to the current platform which is running Node.js is used.
|
||||
|
||||
<a id="ERR_FS_EISDIR"></a>
|
||||
### `ERR_FS_EISDIR`
|
||||
|
||||
Path is a directory.
|
||||
|
||||
<a id="ERR_FS_FILE_TOO_LARGE"></a>
|
||||
### `ERR_FS_FILE_TOO_LARGE`
|
||||
|
||||
|
||||
+78
-9
@@ -3533,9 +3533,9 @@ changes:
|
||||
* `options` {Object}
|
||||
* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
|
||||
`EPERM` error is encountered, Node.js will retry the operation with a linear
|
||||
backoff wait of `retryDelay` ms longer on each try. This option represents
|
||||
the number of retries. This option is ignored if the `recursive` option is
|
||||
not `true`. **Default:** `0`.
|
||||
backoff wait of `retryDelay` milliseconds longer on each try. This option
|
||||
represents the number of retries. This option is ignored if the `recursive`
|
||||
option is not `true`. **Default:** `0`.
|
||||
* `recursive` {boolean} If `true`, perform a recursive directory removal. In
|
||||
recursive mode, errors are not reported if `path` does not exist, and
|
||||
operations are retried on failure. **Default:** `false`.
|
||||
@@ -3584,9 +3584,9 @@ changes:
|
||||
* `options` {Object}
|
||||
* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
|
||||
`EPERM` error is encountered, Node.js will retry the operation with a linear
|
||||
backoff wait of `retryDelay` ms longer on each try. This option represents
|
||||
the number of retries. This option is ignored if the `recursive` option is
|
||||
not `true`. **Default:** `0`.
|
||||
backoff wait of `retryDelay` milliseconds longer on each try. This option
|
||||
represents the number of retries. This option is ignored if the `recursive`
|
||||
option is not `true`. **Default:** `0`.
|
||||
* `recursive` {boolean} If `true`, perform a recursive directory removal. In
|
||||
recursive mode, errors are not reported if `path` does not exist, and
|
||||
operations are retried on failure. **Default:** `false`.
|
||||
@@ -3605,6 +3605,53 @@ that represent files will be deleted. The permissive behavior of the
|
||||
`recursive` option is deprecated, `ENOTDIR` and `ENOENT` will be thrown in
|
||||
the future.
|
||||
|
||||
## `fs.rm(path[, options], callback)`
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `path` {string|Buffer|URL}
|
||||
* `options` {Object}
|
||||
* `force` don't error on nonexistent path
|
||||
* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
|
||||
`EPERM` error is encountered, Node.js will retry the operation with a linear
|
||||
backoff wait of `retryDelay` milliseconds longer on each try. This option
|
||||
represents the number of retries. This option is ignored if the `recursive`
|
||||
option is not `true`. **Default:** `0`.
|
||||
* `recursive` {boolean} If `true`, perform a recursive removal. In
|
||||
recursive mode operations are retried on failure. **Default:** `false`.
|
||||
* `retryDelay` {integer} The amount of time in milliseconds to wait between
|
||||
retries. This option is ignored if the `recursive` option is not `true`.
|
||||
**Default:** `100`.
|
||||
* `callback` {Function}
|
||||
* `err` {Error}
|
||||
|
||||
Asynchronously removes files and directories (modeled on the standard POSIX `rm`
|
||||
utility). No arguments other than a possible exception are given to the
|
||||
completion callback.
|
||||
|
||||
## `fs.rmSync(path[, options])`
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `path` {string|Buffer|URL}
|
||||
* `options` {Object}
|
||||
* `force` Ignore errors
|
||||
* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
|
||||
`EPERM` error is encountered, Node.js will retry the operation with a linear
|
||||
backoff wait of `retryDelay` milliseconds longer on each try. This option
|
||||
represents the number of retries. This option is ignored if the `recursive`
|
||||
option is not `true`. **Default:** `0`.
|
||||
* `recursive` {boolean} If `true`, perform a recursive directory removal. In
|
||||
recursive mode operations are retried on failure. **Default:** `false`.
|
||||
* `retryDelay` {integer} The amount of time in milliseconds to wait between
|
||||
retries. This option is ignored if the `recursive` option is not `true`.
|
||||
**Default:** `100`.
|
||||
|
||||
Synchronously removes files and directories (modeled on the standard POSIX `rm`
|
||||
utility). Returns `undefined`.
|
||||
|
||||
## `fs.stat(path[, options], callback)`
|
||||
<!-- YAML
|
||||
added: v0.0.2
|
||||
@@ -5477,9 +5524,9 @@ changes:
|
||||
* `options` {Object}
|
||||
* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
|
||||
`EPERM` error is encountered, Node.js will retry the operation with a linear
|
||||
backoff wait of `retryDelay` ms longer on each try. This option represents
|
||||
the number of retries. This option is ignored if the `recursive` option is
|
||||
not `true`. **Default:** `0`.
|
||||
backoff wait of `retryDelay` milliseconds longer on each try. This option
|
||||
represents the number of retries. This option is ignored if the `recursive`
|
||||
option is not `true`. **Default:** `0`.
|
||||
* `recursive` {boolean} If `true`, perform a recursive directory removal. In
|
||||
recursive mode, errors are not reported if `path` does not exist, and
|
||||
operations are retried on failure. **Default:** `false`.
|
||||
@@ -5501,6 +5548,28 @@ that represent files will be deleted. The permissive behavior of the
|
||||
`recursive` option is deprecated, `ENOTDIR` and `ENOENT` will be thrown in
|
||||
the future.
|
||||
|
||||
## `fsPromises.rm(path[, options])`
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `path` {string|Buffer|URL}
|
||||
* `options` {Object}
|
||||
* `force` Ignore errors
|
||||
* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
|
||||
`EPERM` error is encountered, Node.js will retry the operation with a linear
|
||||
backoff wait of `retryDelay` milliseconds longer on each try. This option
|
||||
represents the number of retries. This option is ignored if the `recursive`
|
||||
option is not `true`. **Default:** `0`.
|
||||
* `recursive` {boolean} If `true`, perform a recursive directory removal. In
|
||||
recursive mode operations are retried on failure. **Default:** `false`.
|
||||
* `retryDelay` {integer} The amount of time in milliseconds to wait between
|
||||
retries. This option is ignored if the `recursive` option is not `true`.
|
||||
**Default:** `100`.
|
||||
|
||||
Synchronously removes files and directories (modeled on the standard POSIX `rm`
|
||||
utility). Resolves the `Promise` with no arguments on success.
|
||||
|
||||
### `fsPromises.stat(path[, options])`
|
||||
<!-- YAML
|
||||
added: v10.0.0
|
||||
|
||||
@@ -97,6 +97,8 @@ const {
|
||||
validateOffsetLengthRead,
|
||||
validateOffsetLengthWrite,
|
||||
validatePath,
|
||||
validateRmOptions,
|
||||
validateRmOptionsSync,
|
||||
validateRmdirOptions,
|
||||
validateStringAfterArrayBufferView,
|
||||
warnOnNonPortableTemplate
|
||||
@@ -855,30 +857,63 @@ function rmdir(path, options, callback) {
|
||||
|
||||
callback = makeCallback(callback);
|
||||
path = pathModule.toNamespacedPath(getValidatedPath(path));
|
||||
options = validateRmdirOptions(options);
|
||||
|
||||
if (options.recursive) {
|
||||
lazyLoadRimraf();
|
||||
return rimraf(path, options, callback);
|
||||
if (options && options.recursive) {
|
||||
options = validateRmOptions(
|
||||
path,
|
||||
{ ...options, force: true },
|
||||
(err, options) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
lazyLoadRimraf();
|
||||
return rimraf(path, options, callback);
|
||||
});
|
||||
|
||||
} else {
|
||||
options = validateRmdirOptions(options);
|
||||
const req = new FSReqCallback();
|
||||
req.oncomplete = callback;
|
||||
return binding.rmdir(path, req);
|
||||
}
|
||||
|
||||
const req = new FSReqCallback();
|
||||
req.oncomplete = callback;
|
||||
binding.rmdir(path, req);
|
||||
}
|
||||
|
||||
function rmdirSync(path, options) {
|
||||
path = getValidatedPath(path);
|
||||
options = validateRmdirOptions(options);
|
||||
|
||||
if (options.recursive) {
|
||||
if (options && options.recursive) {
|
||||
options = validateRmOptionsSync(path, { ...options, force: true });
|
||||
lazyLoadRimraf();
|
||||
return rimrafSync(pathModule.toNamespacedPath(path), options);
|
||||
}
|
||||
|
||||
options = validateRmdirOptions(options);
|
||||
const ctx = { path };
|
||||
binding.rmdir(pathModule.toNamespacedPath(path), undefined, ctx);
|
||||
handleErrorFromBinding(ctx);
|
||||
return handleErrorFromBinding(ctx);
|
||||
}
|
||||
|
||||
function rm(path, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = undefined;
|
||||
}
|
||||
|
||||
validateRmOptions(path, options, (err, options) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
lazyLoadRimraf();
|
||||
return rimraf(pathModule.toNamespacedPath(path), options, callback);
|
||||
});
|
||||
}
|
||||
|
||||
function rmSync(path, options) {
|
||||
options = validateRmOptionsSync(path, options);
|
||||
|
||||
lazyLoadRimraf();
|
||||
return rimrafSync(pathModule.toNamespacedPath(path), options);
|
||||
}
|
||||
|
||||
function fdatasync(fd, callback) {
|
||||
@@ -2040,6 +2075,8 @@ module.exports = fs = {
|
||||
realpathSync,
|
||||
rename,
|
||||
renameSync,
|
||||
rm,
|
||||
rmSync,
|
||||
rmdir,
|
||||
rmdirSync,
|
||||
stat,
|
||||
|
||||
@@ -843,6 +843,7 @@ E('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM',
|
||||
'The feature %s is unavailable on the current platform' +
|
||||
', which is being used to run Node.js',
|
||||
TypeError);
|
||||
E('ERR_FS_EISDIR', 'Path is a directory', SystemError);
|
||||
E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GB', RangeError);
|
||||
E('ERR_FS_INVALID_SYMLINK_TYPE',
|
||||
'Symlink type must be one of "dir", "file", or "junction". Received "%s"',
|
||||
|
||||
@@ -52,6 +52,7 @@ const {
|
||||
validateBufferArray,
|
||||
validateOffsetLengthRead,
|
||||
validateOffsetLengthWrite,
|
||||
validateRmOptions,
|
||||
validateRmdirOptions,
|
||||
validateStringAfterArrayBufferView,
|
||||
warnOnNonPortableTemplate
|
||||
@@ -79,6 +80,7 @@ const {
|
||||
} = require('internal/worker/js_transferable');
|
||||
|
||||
const getDirectoryEntriesPromise = promisify(getDirents);
|
||||
const validateRmOptionsPromise = promisify(validateRmOptions);
|
||||
|
||||
class FileHandle extends JSTransferable {
|
||||
constructor(filehandle) {
|
||||
@@ -417,6 +419,12 @@ async function ftruncate(handle, len = 0) {
|
||||
return binding.ftruncate(handle.fd, len, kUsePromises);
|
||||
}
|
||||
|
||||
async function rm(path, options) {
|
||||
path = pathModule.toNamespacedPath(getValidatedPath(path));
|
||||
options = await validateRmOptionsPromise(path, options);
|
||||
return rimrafPromises(path, options);
|
||||
}
|
||||
|
||||
async function rmdir(path, options) {
|
||||
path = pathModule.toNamespacedPath(getValidatedPath(path));
|
||||
options = validateRmdirOptions(options);
|
||||
@@ -635,6 +643,7 @@ module.exports = {
|
||||
opendir: promisify(opendir),
|
||||
rename,
|
||||
truncate,
|
||||
rm,
|
||||
rmdir,
|
||||
mkdir,
|
||||
readdir,
|
||||
|
||||
+87
-10
@@ -17,6 +17,7 @@ const {
|
||||
const { Buffer } = require('buffer');
|
||||
const {
|
||||
codes: {
|
||||
ERR_FS_EISDIR,
|
||||
ERR_FS_INVALID_SYMLINK_TYPE,
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_ARG_VALUE,
|
||||
@@ -650,29 +651,103 @@ function warnOnNonPortableTemplate(template) {
|
||||
}
|
||||
}
|
||||
|
||||
const defaultRmOptions = {
|
||||
recursive: false,
|
||||
force: false,
|
||||
retryDelay: 100,
|
||||
maxRetries: 0
|
||||
};
|
||||
|
||||
const defaultRmdirOptions = {
|
||||
retryDelay: 100,
|
||||
maxRetries: 0,
|
||||
recursive: false,
|
||||
};
|
||||
|
||||
const validateRmdirOptions = hideStackFrames((options) => {
|
||||
if (options === undefined)
|
||||
return defaultRmdirOptions;
|
||||
if (options === null || typeof options !== 'object')
|
||||
throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
|
||||
const validateRmOptions = hideStackFrames((path, options, callback) => {
|
||||
try {
|
||||
options = validateRmdirOptions(options, defaultRmOptions);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
options = { ...defaultRmdirOptions, ...options };
|
||||
if (typeof options.force !== 'boolean')
|
||||
return callback(
|
||||
new ERR_INVALID_ARG_TYPE('force', 'boolean', options.force)
|
||||
);
|
||||
|
||||
if (typeof options.recursive !== 'boolean')
|
||||
throw new ERR_INVALID_ARG_TYPE('recursive', 'boolean', options.recursive);
|
||||
lazyLoadFs().stat(path, (err, stats) => {
|
||||
if (err && err.code === 'ENOENT') {
|
||||
if (options.force) {
|
||||
return callback(null, options);
|
||||
}
|
||||
return callback(err, options);
|
||||
}
|
||||
|
||||
validateInt32(options.retryDelay, 'retryDelay', 0);
|
||||
validateUint32(options.maxRetries, 'maxRetries');
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
if (stats.isDirectory() && !options.recursive) {
|
||||
return callback(new ERR_FS_EISDIR({
|
||||
code: 'EISDIR',
|
||||
message: 'is a directory',
|
||||
path,
|
||||
syscall: 'rm',
|
||||
errno: -21
|
||||
}));
|
||||
}
|
||||
return callback(null, options);
|
||||
});
|
||||
});
|
||||
|
||||
const validateRmOptionsSync = hideStackFrames((path, options) => {
|
||||
options = validateRmdirOptions(options, defaultRmOptions);
|
||||
|
||||
if (typeof options.force !== 'boolean')
|
||||
throw new ERR_INVALID_ARG_TYPE('force', 'boolean', options.force);
|
||||
|
||||
try {
|
||||
const stats = lazyLoadFs().statSync(path);
|
||||
|
||||
if (stats.isDirectory() && !options.recursive) {
|
||||
throw new ERR_FS_EISDIR({
|
||||
code: 'EISDIR',
|
||||
message: 'is a directory',
|
||||
path,
|
||||
syscall: 'rm',
|
||||
errno: -21
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
throw err;
|
||||
} else if (err.code === 'ENOENT' && !options.force) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
});
|
||||
|
||||
const validateRmdirOptions = hideStackFrames(
|
||||
(options, defaults = defaultRmdirOptions) => {
|
||||
if (options === undefined)
|
||||
return defaults;
|
||||
if (options === null || typeof options !== 'object')
|
||||
throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
|
||||
|
||||
options = { ...defaults, ...options };
|
||||
|
||||
if (typeof options.recursive !== 'boolean')
|
||||
throw new ERR_INVALID_ARG_TYPE('recursive', 'boolean', options.recursive);
|
||||
|
||||
validateInt32(options.retryDelay, 'retryDelay', 0);
|
||||
validateUint32(options.maxRetries, 'maxRetries');
|
||||
|
||||
return options;
|
||||
});
|
||||
|
||||
const getValidMode = hideStackFrames((mode, type) => {
|
||||
let min = kMinimumAccessMode;
|
||||
let max = kMaximumAccessMode;
|
||||
@@ -741,6 +816,8 @@ module.exports = {
|
||||
validateOffsetLengthRead,
|
||||
validateOffsetLengthWrite,
|
||||
validatePath,
|
||||
validateRmOptions,
|
||||
validateRmOptionsSync,
|
||||
validateRmdirOptions,
|
||||
validateStringAfterArrayBufferView,
|
||||
warnOnNonPortableTemplate
|
||||
|
||||
@@ -5,8 +5,8 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { isMainThread } = require('worker_threads');
|
||||
|
||||
function rimrafSync(pathname) {
|
||||
fs.rmdirSync(pathname, { maxRetries: 3, recursive: true });
|
||||
function rmSync(pathname) {
|
||||
fs.rmSync(pathname, { maxRetries: 3, recursive: true, force: true });
|
||||
}
|
||||
|
||||
const testRoot = process.env.NODE_TEST_DIR ?
|
||||
@@ -20,7 +20,7 @@ const tmpPath = path.join(testRoot, tmpdirName);
|
||||
|
||||
let firstRefresh = true;
|
||||
function refresh() {
|
||||
rimrafSync(this.path);
|
||||
rmSync(this.path);
|
||||
fs.mkdirSync(this.path);
|
||||
|
||||
if (firstRefresh) {
|
||||
@@ -37,7 +37,7 @@ function onexit() {
|
||||
process.chdir(testRoot);
|
||||
|
||||
try {
|
||||
rimrafSync(tmpPath);
|
||||
rmSync(tmpPath);
|
||||
} catch (e) {
|
||||
console.error('Can\'t clean tmpdir:', tmpPath);
|
||||
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
// Flags: --expose-internals
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
const tmpdir = require('../common/tmpdir');
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { validateRmOptionsSync } = require('internal/fs/utils');
|
||||
|
||||
tmpdir.refresh();
|
||||
|
||||
let count = 0;
|
||||
const nextDirPath = (name = 'rm') =>
|
||||
path.join(tmpdir.path, `${name}-${count++}`);
|
||||
|
||||
function makeNonEmptyDirectory(depth, files, folders, dirname, createSymLinks) {
|
||||
fs.mkdirSync(dirname, { recursive: true });
|
||||
fs.writeFileSync(path.join(dirname, 'text.txt'), 'hello', 'utf8');
|
||||
|
||||
const options = { flag: 'wx' };
|
||||
|
||||
for (let f = files; f > 0; f--) {
|
||||
fs.writeFileSync(path.join(dirname, `f-${depth}-${f}`), '', options);
|
||||
}
|
||||
|
||||
if (createSymLinks) {
|
||||
// Valid symlink
|
||||
fs.symlinkSync(
|
||||
`f-${depth}-1`,
|
||||
path.join(dirname, `link-${depth}-good`),
|
||||
'file'
|
||||
);
|
||||
|
||||
// Invalid symlink
|
||||
fs.symlinkSync(
|
||||
'does-not-exist',
|
||||
path.join(dirname, `link-${depth}-bad`),
|
||||
'file'
|
||||
);
|
||||
}
|
||||
|
||||
// File with a name that looks like a glob
|
||||
fs.writeFileSync(path.join(dirname, '[a-z0-9].txt'), '', options);
|
||||
|
||||
depth--;
|
||||
if (depth <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let f = folders; f > 0; f--) {
|
||||
fs.mkdirSync(
|
||||
path.join(dirname, `folder-${depth}-${f}`),
|
||||
{ recursive: true }
|
||||
);
|
||||
makeNonEmptyDirectory(
|
||||
depth,
|
||||
files,
|
||||
folders,
|
||||
path.join(dirname, `d-${depth}-${f}`),
|
||||
createSymLinks
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function removeAsync(dir) {
|
||||
// Removal should fail without the recursive option.
|
||||
fs.rm(dir, common.mustCall((err) => {
|
||||
assert.strictEqual(err.syscall, 'rm');
|
||||
|
||||
// Removal should fail without the recursive option set to true.
|
||||
fs.rm(dir, { recursive: false }, common.mustCall((err) => {
|
||||
assert.strictEqual(err.syscall, 'rm');
|
||||
|
||||
// Recursive removal should succeed.
|
||||
fs.rm(dir, { recursive: true }, common.mustCall((err) => {
|
||||
assert.ifError(err);
|
||||
|
||||
// Attempted removal should fail now because the directory is gone.
|
||||
fs.rm(dir, common.mustCall((err) => {
|
||||
assert.strictEqual(err.syscall, 'stat');
|
||||
}));
|
||||
}));
|
||||
}));
|
||||
}));
|
||||
}
|
||||
|
||||
// Test the asynchronous version
|
||||
{
|
||||
// Create a 4-level folder hierarchy including symlinks
|
||||
let dir = nextDirPath();
|
||||
makeNonEmptyDirectory(4, 10, 2, dir, true);
|
||||
removeAsync(dir);
|
||||
|
||||
// Create a 2-level folder hierarchy without symlinks
|
||||
dir = nextDirPath();
|
||||
makeNonEmptyDirectory(2, 10, 2, dir, false);
|
||||
removeAsync(dir);
|
||||
|
||||
// Create a flat folder including symlinks
|
||||
dir = nextDirPath();
|
||||
makeNonEmptyDirectory(1, 10, 2, dir, true);
|
||||
removeAsync(dir);
|
||||
|
||||
// Should fail if target does not exist
|
||||
fs.rm(
|
||||
path.join(tmpdir.path, 'noexist.txt'),
|
||||
{ recursive: true },
|
||||
common.mustCall((err) => {
|
||||
assert.strictEqual(err.code, 'ENOENT');
|
||||
})
|
||||
);
|
||||
|
||||
// Should delete a file
|
||||
const filePath = path.join(tmpdir.path, 'rm-async-file.txt');
|
||||
fs.writeFileSync(filePath, '');
|
||||
fs.rm(filePath, { recursive: true }, common.mustCall((err) => {
|
||||
try {
|
||||
assert.strictEqual(err, null);
|
||||
assert.strictEqual(fs.existsSync(filePath), false);
|
||||
} finally {
|
||||
fs.rmSync(filePath, { force: true });
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
// Test the synchronous version.
|
||||
{
|
||||
const dir = nextDirPath();
|
||||
makeNonEmptyDirectory(4, 10, 2, dir, true);
|
||||
|
||||
// Removal should fail without the recursive option set to true.
|
||||
assert.throws(() => {
|
||||
fs.rmSync(dir);
|
||||
}, { syscall: 'rm' });
|
||||
assert.throws(() => {
|
||||
fs.rmSync(dir, { recursive: false });
|
||||
}, { syscall: 'rm' });
|
||||
|
||||
// Should fail if target does not exist
|
||||
assert.throws(() => {
|
||||
fs.rmSync(path.join(tmpdir.path, 'noexist.txt'), { recursive: true });
|
||||
}, {
|
||||
code: 'ENOENT',
|
||||
name: 'Error',
|
||||
message: /^ENOENT: no such file or directory, stat/
|
||||
});
|
||||
|
||||
// Should delete a file
|
||||
const filePath = path.join(tmpdir.path, 'rm-file.txt');
|
||||
fs.writeFileSync(filePath, '');
|
||||
|
||||
try {
|
||||
fs.rmSync(filePath, { recursive: true });
|
||||
} finally {
|
||||
fs.rmSync(filePath, { force: true });
|
||||
}
|
||||
|
||||
// Recursive removal should succeed.
|
||||
fs.rmSync(dir, { recursive: true });
|
||||
|
||||
// Attempted removal should fail now because the directory is gone.
|
||||
assert.throws(() => fs.rmSync(dir), { syscall: 'stat' });
|
||||
}
|
||||
|
||||
// Test the Promises based version.
|
||||
(async () => {
|
||||
const dir = nextDirPath();
|
||||
makeNonEmptyDirectory(4, 10, 2, dir, true);
|
||||
|
||||
// Removal should fail without the recursive option set to true.
|
||||
assert.rejects(fs.promises.rm(dir), { syscall: 'rm' });
|
||||
assert.rejects(fs.promises.rm(dir, { recursive: false }), {
|
||||
syscall: 'rm'
|
||||
});
|
||||
|
||||
// Recursive removal should succeed.
|
||||
await fs.promises.rm(dir, { recursive: true });
|
||||
|
||||
// Attempted removal should fail now because the directory is gone.
|
||||
assert.rejects(fs.promises.rm(dir), { syscall: 'stat' });
|
||||
|
||||
// Should fail if target does not exist
|
||||
assert.rejects(fs.promises.rm(
|
||||
path.join(tmpdir.path, 'noexist.txt'),
|
||||
{ recursive: true }
|
||||
), {
|
||||
code: 'ENOENT',
|
||||
name: 'Error',
|
||||
message: /^ENOENT: no such file or directory, stat/
|
||||
});
|
||||
|
||||
// Should not fail if target does not exist and force option is true
|
||||
fs.promises.rm(path.join(tmpdir.path, 'noexist.txt'), { force: true });
|
||||
|
||||
// Should delete file
|
||||
const filePath = path.join(tmpdir.path, 'rm-promises-file.txt');
|
||||
fs.writeFileSync(filePath, '');
|
||||
|
||||
try {
|
||||
await fs.promises.rm(filePath, { recursive: true });
|
||||
} finally {
|
||||
fs.rmSync(filePath, { force: true });
|
||||
}
|
||||
})().then(common.mustCall());
|
||||
|
||||
// Test input validation.
|
||||
{
|
||||
const dir = nextDirPath();
|
||||
makeNonEmptyDirectory(4, 10, 2, dir, true);
|
||||
const filePath = (path.join(tmpdir.path, 'rm-args-file.txt'));
|
||||
fs.writeFileSync(filePath, '');
|
||||
|
||||
const defaults = {
|
||||
retryDelay: 100,
|
||||
maxRetries: 0,
|
||||
recursive: false,
|
||||
force: false
|
||||
};
|
||||
const modified = {
|
||||
retryDelay: 953,
|
||||
maxRetries: 5,
|
||||
recursive: true,
|
||||
force: false
|
||||
};
|
||||
|
||||
assert.deepStrictEqual(validateRmOptionsSync(filePath), defaults);
|
||||
assert.deepStrictEqual(validateRmOptionsSync(filePath, {}), defaults);
|
||||
assert.deepStrictEqual(validateRmOptionsSync(filePath, modified), modified);
|
||||
assert.deepStrictEqual(validateRmOptionsSync(filePath, {
|
||||
maxRetries: 99
|
||||
}), {
|
||||
retryDelay: 100,
|
||||
maxRetries: 99,
|
||||
recursive: false,
|
||||
force: false
|
||||
});
|
||||
|
||||
[null, 'foo', 5, NaN].forEach((bad) => {
|
||||
assert.throws(() => {
|
||||
validateRmOptionsSync(filePath, bad);
|
||||
}, {
|
||||
code: 'ERR_INVALID_ARG_TYPE',
|
||||
name: 'TypeError',
|
||||
message: /^The "options" argument must be of type object\./
|
||||
});
|
||||
});
|
||||
|
||||
[undefined, null, 'foo', Infinity, function() {}].forEach((bad) => {
|
||||
assert.throws(() => {
|
||||
validateRmOptionsSync(filePath, { recursive: bad });
|
||||
}, {
|
||||
code: 'ERR_INVALID_ARG_TYPE',
|
||||
name: 'TypeError',
|
||||
message: /^The "recursive" argument must be of type boolean\./
|
||||
});
|
||||
});
|
||||
|
||||
[undefined, null, 'foo', Infinity, function() {}].forEach((bad) => {
|
||||
assert.throws(() => {
|
||||
validateRmOptionsSync(filePath, { force: bad });
|
||||
}, {
|
||||
code: 'ERR_INVALID_ARG_TYPE',
|
||||
name: 'TypeError',
|
||||
message: /^The "force" argument must be of type boolean\./
|
||||
});
|
||||
});
|
||||
|
||||
assert.throws(() => {
|
||||
validateRmOptionsSync(filePath, { retryDelay: -1 });
|
||||
}, {
|
||||
code: 'ERR_OUT_OF_RANGE',
|
||||
name: 'RangeError',
|
||||
message: /^The value of "retryDelay" is out of range\./
|
||||
});
|
||||
|
||||
assert.throws(() => {
|
||||
validateRmOptionsSync(filePath, { maxRetries: -1 });
|
||||
}, {
|
||||
code: 'ERR_OUT_OF_RANGE',
|
||||
name: 'RangeError',
|
||||
message: /^The value of "maxRetries" is out of range\./
|
||||
});
|
||||
}
|
||||
@@ -20,7 +20,7 @@ function hash(algo, body) {
|
||||
}
|
||||
|
||||
const tmpdirPath = path.join(tmpdir.path, 'test-policy-parse-integrity');
|
||||
fs.rmdirSync(tmpdirPath, { maxRetries: 3, recursive: true });
|
||||
fs.rmSync(tmpdirPath, { maxRetries: 3, recursive: true, force: true });
|
||||
fs.mkdirSync(tmpdirPath, { recursive: true });
|
||||
|
||||
const policyFilepath = path.join(tmpdirPath, 'policy');
|
||||
|
||||
@@ -109,7 +109,7 @@ function drainQueue() {
|
||||
`deletable-policy-${testId}.json`
|
||||
);
|
||||
const cliPolicy = willDeletePolicy ? tmpPolicyPath : policyPath;
|
||||
fs.rmdirSync(configDirPath, { maxRetries: 3, recursive: true });
|
||||
fs.rmSync(configDirPath, { maxRetries: 3, recursive: true, force: true });
|
||||
fs.mkdirSync(configDirPath, { recursive: true });
|
||||
const manifest = {
|
||||
onerror: onError,
|
||||
@@ -185,7 +185,7 @@ function drainQueue() {
|
||||
console.log(`stderr: ${Buffer.concat(stderr)}`);
|
||||
throw e;
|
||||
}
|
||||
fs.rmdirSync(configDirPath, { maxRetries: 3, recursive: true });
|
||||
fs.rmSync(configDirPath, { maxRetries: 3, recursive: true, force: true });
|
||||
drainQueue();
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user