fs-extender
Version:
Extras suite for node fs module
534 lines • 22.2 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.opendir = exports.writeFile = exports.utimes = exports.unlink = exports.truncate = exports.symlink = exports.statIsSymbolicLink = exports.statIsFile = exports.statIsDirectory = exports.lstat = exports.fstat = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.realpath = exports.readlink = exports.readFile = exports.readDir = exports.readdir = exports.read = exports.open = exports.mkdtemp = exports.mkdir = exports.lutimes = exports.link = exports.isEmpty = exports.existAccess = exports.exists = exports.cp = exports.lchomd = exports.fchmod = exports.chmod = exports.lchown = exports.fchown = exports.chown = exports.copyFile = exports.appendFile = exports.access = void 0;
const fsAux = process.env["FS_EXTENDER_FS_OVERRIDE"] ? require(process.env["FS_EXTENDER_FS_OVERRIDE"]) : require("fs");
const util_1 = require("util");
const fs = __importStar(require("./patch"));
const _rm = __importStar(require("../rm"));
const _copy = __importStar(require("../copy"));
Object.keys(fsAux.promises).forEach((key) => {
module.exports[key] = fsAux.promises[key];
});
/**
* Tests a user's permissions for the file or directory specified by `path`.
* The `mode` argument is an optional integer that specifies the accessibility
* checks to be performed. Check `File access constants` for possible values
* of `mode`. It is possible to create a mask consisting of the bitwise OR of
* two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
*
* If the accessibility check is successful, the promise is resolved with no
* value. If any of the accessibility checks fail, the promise is rejected
* with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object.
* The following example checks if the file`/etc/passwd` can be read and
* written by the current process.
*
* ```js
* import * as fs from "fs-extender";
*
* try {
* await fs.promises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
* console.log('can access');
* } catch {
* console.error('cannot access');
* }
* ```
*
* Using `fs.promises.access()` to check for the accessibility of a file before
* calling `fs.promises.open()` is not recommended. Doing so introduces a race
* condition, since other processes may change the file's state between the two
* calls. Instead, user code should open/read/write the file directly and handle
* the error raised if the file is not accessible.
* @param [mode=fs.constants.F_OK]
* @return Fulfills with `undefined` upon success.
*/
function access(path, mode) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.access), fs, [path, mode]);
}
exports.access = access;
/**
* Asynchronously append data to a file, creating the file if it does not exist.
* @param file A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `mode` is not supplied, the default of `0o666` is used.
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'a'` is used.
*/
function appendFile(file, data, options) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.appendFile), fs, [file, data, options]);
}
exports.appendFile = appendFile;
/**
* Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
* already exists. No arguments other than a possible exception are given to the
* callback function. Node.js makes no guarantees about the atomicity of the copy
* operation. If an error occurs after the destination file has been opened for
* writing, Node.js will attempt to remove the destination.
*
* `mode` is an optional integer that specifies the behavior
* of the copy operation. It is possible to create a mask consisting of the bitwise
* OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
*
* * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
* exists.
* * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
* copy-on-write reflink. If the platform does not support copy-on-write, then a
* fallback copy mechanism is used.
* * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
* create a copy-on-write reflink. If the platform does not support
* copy-on-write, then the operation will fail.
*
* ```js
* import * as fs from "fs-extender";
*
* // destination.txt will be created or overwritten by default.
* fs.promises.copyFile('source.txt', 'destination.txt');
*
* // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
* fs.promises.copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
* ```
* @param src source filename to copy
* @param dest destination filename of the copy operation
* @param [mode=0] modifiers for copy operation.
*/
function copyFile(src, dst, mode) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.copyFile), fs, [src, dst, mode]);
}
exports.copyFile = copyFile;
/**
* Asynchronous chown(2) - Change ownership of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function chown(path, uid, gid) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.chown), fs, [path, uid, gid]);
}
exports.chown = chown;
/**
* Asynchronous fchown(2) - Change ownership of a file.
* @param fd A file descriptor.
*/
function fchown(fd, uid, gid) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.fchown), fs, [fd, uid, gid]);
}
exports.fchown = fchown;
/**
* Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function lchown(path, uid, gid) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.lchown), fs, [path, uid, gid]);
}
exports.lchown = lchown;
/**
* Asynchronous chmod(2) - Change permissions of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/
function chmod(path, mode) {
return Reflect.apply((0, util_1.promisify)(fs.chmod), fs, [path, mode]);
}
exports.chmod = chmod;
/**
* Asynchronous fchmod(2) - Change permissions of a file.
* @param fd A file descriptor.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/
function fchmod(fd, mode) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.fchmod), fs, [fd, mode]);
}
exports.fchmod = fchmod;
/**
* Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/
function lchomd(path, mode) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.lchmod), fs, [path, mode]);
}
exports.lchomd = lchomd;
/**
* Asynchronously copies the entire directory structure from `src` to `dest`,
* including subdirectories and files.
*
* When copying a directory to another directory, globs are not supported and
* behavior is similar to `cp dir1/ dir2/`.
* if cp function doesn't exist in fs.promises then the copy module will be used
* this is normalized so that there's always an option to copy files without failing
* because cp was introduced as experimental at node v16.7.0
* @param src source path to copy.
* @param dest destination path to copy to.
* @return Fulfills with `undefined` upon success.
*/
function cp(source, destination, opts) {
/* istanbul ignore next */
if ("promises" in fsAux && "cp" in fsAux.promises) {
return Reflect.apply(fsAux.promises.cp, fsAux, [source, destination, opts]);
}
else {
return Reflect.apply(_copy.promises.copy, fs, [source, destination, opts]);
}
}
exports.cp = cp;
/**
* @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
*/
function exists(path) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.exists), fs, [path]);
}
exports.exists = exists;
/**
* Check if it is possible to access the `path` object
* `callback` gets 2 arguments `(err, exist:boolean)`
* @param path fs.PathLike
* @param mode
*/
function existAccess(path, mode) {
return Reflect.apply((0, util_1.promisify)(fs.existAccess), fs, [path, mode]);
}
exports.existAccess = existAccess;
/**
* Check if given path is empty, if it's a folder it will use
* `readdir` and check the number of returing items,
* if it's another thing it will return the `size === 0`.
* Will throw any error that happens while checking
*/
function isEmpty(path, options = { dereference: false }) {
return Reflect.apply((0, util_1.promisify)(fs.isEmpty), fs, [path, options]);
}
exports.isEmpty = isEmpty;
/**
* Creates a new link from the `existingPath` to the `newPath`.
* See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail.
* @return Fulfills with `undefined` upon success.
*/
function link(existingPath, newPath) {
return Reflect.apply((0, util_1.promisify)(fs.link), fs, [existingPath, newPath]);
}
exports.link = link;
/**
* Changes the access and modification times of a file in the same way as `fs.promises.utimes()`,
* with the difference that if the path refers to a symbolic link, then the link is not
* dereferenced: instead, the timestamps of the symbolic link itself are changed.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param atime The last access time. If a string is provided, it will be coerced to number.
* @param mtime The last modified time. If a string is provided, it will be coerced to number.
*/
function lutimes(path, atime, mtime) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.lutimes), fs, [path, atime, mtime]);
}
exports.lutimes = lutimes;
function mkdir(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.mkdir), fs, [path, options]);
}
exports.mkdir = mkdir;
function mkdtemp(prefix, options) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.mkdtemp), fs, [prefix, options]);
}
exports.mkdtemp = mkdtemp;
/**
* Opens a `FileHandle`.
*
* Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail.
*
* Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
* by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
* a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
* @param [flags='r'] See `support of file system `flags``.
* @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created.
* @return Fulfills with a {FileHandle} object.
*/
function open(path, flags, mode) {
return Reflect.apply(fsAux.promises.open, fsAux, [path, flags, mode]);
}
exports.open = open;
/**
* Read data from the file specified by `fd`.
*
* The callback is given the three arguments, `(err, bytesRead, buffer)`.
*
* If the file is not modified concurrently, the end-of-file is reached when the
* number of bytes read is zero.
*
* If this method is invoked as its `util.promisify()` ed version, it returns
* a promise for an `Object` with `bytesRead` and `buffer` properties.
* @param buffer The buffer that the data will be written to.
* @param offset The position in `buffer` to write the data to.
* @param length The number of bytes to read.
* @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If
* `position` is an integer, the file position will be unchanged.
*/
function read(fd, buffer, offset, length, position) {
/* istanbul ignore next */
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) {
return reject(err);
}
resolve({ bytesRead, buffer });
});
});
}
exports.read = read;
function readdir(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.readdir), fs, [path, options]);
}
exports.readdir = readdir;
function readDir(path, options) {
/* istanbul ignore next */
return readdir(path, options);
}
exports.readDir = readDir;
function readFile(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.readFile), fs, [path, options]);
}
exports.readFile = readFile;
function readlink(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.readlink), fs, [path, options]);
}
exports.readlink = readlink;
function realpath(path, options) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.realpath), fs, [path, options]);
}
exports.realpath = realpath;
/**
* Asynchronous rename(2) - Change the name or location of a file or directory.
* @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
*/
function rename(oldPath, newPath) {
return Reflect.apply((0, util_1.promisify)(fs.rename), fs, [oldPath, newPath]);
}
exports.rename = rename;
/**
* Removes files and directories (modeled on the standard POSIX `rm` utility).
* if rm method doesn't exist in fs.promises, the rm method will be used instead
* @return Fulfills with `undefined` upon success.
*/
function rm(path, options) {
/* istanbul ignore next */
if ("promises" in fsAux && "rm" in fsAux.promises) {
return Reflect.apply(fsAux.promises.rm, fsAux, [path, options]);
}
else {
return Reflect.apply(_rm.promises.rm, fs, [path, options]);
}
}
exports.rm = rm;
/**
* Removes the directory identified by `path`.
*
* Using `fsPromises.rmdir()` on a file (not a directory) results in the
* promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX.
*
* To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`.
* @return Fulfills with `undefined` upon success.
*/
function rmdir(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.rmdir), fs, [path, options]);
}
exports.rmdir = rmdir;
function stat(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.stat), fs, [path, options]);
}
exports.stat = stat;
function fstat(fd, options) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.fstat), fs, [fd, options]);
}
exports.fstat = fstat;
function lstat(path, options) {
return Reflect.apply((0, util_1.promisify)(fs.lstat), fs, [path, options]);
}
exports.lstat = lstat;
/**
* Check if path is a directory
* @param path
* @returns
*/
function statIsDirectory(path) {
return new Promise((resolve, reject) => {
fs.statIsDirectory(path, (err, isType, stats) => {
if (err) {
/* istanbul ignore next */
return reject(err);
}
resolve({ isType, stats });
});
});
}
exports.statIsDirectory = statIsDirectory;
/**
* Check if path is a file
* @param path
* @returns
*/
function statIsFile(path) {
return new Promise((resolve, reject) => {
fs.statIsFile(path, (err, isType, stats) => {
if (err) {
/* istanbul ignore next */
return reject(err);
}
resolve({ isType, stats });
});
});
}
exports.statIsFile = statIsFile;
/**
* Check if path is a symbolik link
* @param path
* @returns
*/
function statIsSymbolicLink(path) {
/* istanbul ignore next */
return new Promise((resolve, reject) => {
fs.statIsSymbolicLink(path, (err, isType, stats) => {
if (err) {
return reject(err);
}
resolve({ isType, stats });
});
});
}
exports.statIsSymbolicLink = statIsSymbolicLink;
/**
* Creates a symbolic link.
*
* The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`.
* Windows junction points require the destination path
* to be absolute. When using `'junction'`, the `target` argument will
* automatically be normalized to absolute path.
* @param [type='file']
* @return Fulfills with `undefined` upon success.
*/
function symlink(target, path, type) {
return Reflect.apply((0, util_1.promisify)(fs.symlink), fs, [target, path, type]);
}
exports.symlink = symlink;
/**
* Truncates (shortens or extends the length) of the content at `path` to `len`bytes.
* @param [len=0]
* @return Fulfills with `undefined` upon success.
*/
function truncate(path, len) {
/* istanbul ignore next */
return Reflect.apply((0, util_1.promisify)(fs.truncate), fs, [path, len]);
}
exports.truncate = truncate;
/**
* If `path` refers to a symbolic link, then the link is removed without affecting
* the file or directory to which that link refers. If the `path` refers to a file
* path that is not a symbolic link, the file is deleted.
* See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail.
* @return Fulfills with `undefined` upon success.
*/
function unlink(path) {
return Reflect.apply((0, util_1.promisify)(fs.unlink), fs, [path]);
}
exports.unlink = unlink;
/**
* Change the file system timestamps of the object referenced by `path`.
*
* The `atime` and `mtime` arguments follow these rules:
*
* * Values can be either numbers representing Unix epoch time, `Date`s, or a
* numeric string like `'123456789.0'`.
* * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown.
* @return Fulfills with `undefined` upon success.
*/
function utimes(path, atime, mtime) {
return Reflect.apply((0, util_1.promisify)(fs.utimes), fs, [path, atime, mtime]);
}
exports.utimes = utimes;
/**
* Asynchronously writes data to a file, replacing the file if it already exists.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `mode` is not supplied, the default of `0o666` is used.
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'w'` is used.
*/
function writeFile(path, data, options) {
return Reflect.apply((0, util_1.promisify)(fs.writeFile), fs, [path, data, options]);
}
exports.writeFile = writeFile;
/**
* Asynchronously open a directory for iterative scanning.
* See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail.
*
* Creates an `fs.Dir`, which contains all further functions for reading from
* and cleaning up the directory.
*
* The `encoding` option sets the encoding for the `path` while opening the
* directory and subsequent read operations.
*
* Example using async iteration:
*
* ```js
* import { opendir } from 'fs/promises';
*
* try {
* const dir = await opendir('./');
* for await (const dirent of dir)
* console.log(dirent.name);
* } catch (err) {
* console.error(err);
* }
* ```
*
* When using the async iterator, the `fs.Dir` object will be automatically
* closed after the iterator exits.
* @return Fulfills with an {fs.Dir}.
*/
function opendir(path, options) {
/* istanbul ignore next */
if ("promises" in fsAux && "opendir" in fsAux.promises) {
return Reflect.apply(fsAux.promises.opendir, fsAux, [path, options]);
}
else {
throw new Error("To be implemented");
}
}
exports.opendir = opendir;
//# sourceMappingURL=promises.js.map
;