pwd-fs
v3.5.10
Published
Path-aware file system utilities with scoped working directories and recursive operations
Maintainers
Readme
Powered File System
This module extends the Node.js® file system API with a declared pwd (working directory) and recursive execution helpers. By default, all file system operations have asynchronous forms. The API provides an alternative set of asynchronous file system methods that return Promise objects.
Getting Started
Installation
To use Powered File System in your project, run:
npm install pwd-fsConsumer Guides
See the consumer guides for task-oriented examples covering scoped paths, common file workflows, and synchronous execution.
Table of Contents
- constructor: new PoweredFileSystem([path])
- pfs.test(src[, options])
- pfs.stat(src[, options])
- pfs.chmod(src, mode[, options])
- pfs.chown(src[, options])
- pfs.symlink(src, dest[, options])
- pfs.copy(src, dir[, options])
- pfs.rename(src, dest[, options])
- pfs.remove(src[, options])
- pfs.emptyDir(src[, options])
- pfs.read(src[, options])
- pfs.write(src, data[, options])
- pfs.append(src, data[, options])
- pfs.readdir(dir[, options])
- pfs.readlink(src[, options])
- pfs.realpath(src[, options])
- pfs.mkdir(dir[, options])
- pfs.pwd
- static: bitmask(mode)
The class methods are divided into resource groups.
| Resource | Methods |
|-----------------------------|------------------------------------------------------------------|
| Common (file and directory) | chmod chown copy realpath remove rename stat test |
| File only | append read write |
| Directory only | emptyDir mkdir readdir |
| Link only | readlink symlink |
class PoweredFileSystem
This class is implemented in TypeScript and follows Node.js file system semantics.
constructor: new PoweredFileSystem([path])
path<String> Absolute or relative directory name.pathsets thepfs.pwdvalue. By default, it is process.cwd().
String paths are interpreted as UTF-8 character sequences identifying absolute or relative file names.
import { pfs } from 'pwd-fs';
// pfs.pwd === process.cwd()Relative paths will be resolved relative to the current working directory as specified by process.cwd():
import { PoweredFileSystem } from 'pwd-fs';
// pfs.pwd === `${process.cwd()}/foo/bar`
const pfs = new PoweredFileSystem('./foo/bar');Absolute paths:
import { PoweredFileSystem } from 'pwd-fs';
// pfs.pwd === __dirname
const pfs = new PoweredFileSystem(__dirname);pfs.test(src[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.options<Object>- returns: <Promise> Resolves with a
boolean.
Tests a user's permissions for the file or directory specified by path.
const access = await pfs.test('./path');
console.log(access); // trueFunction
pfs.test()resolves withfalsefor access errors instead of rejecting.
The following flag values are meant for use with pfs.test().
Flag | Description
-----|-------------
'e' | Source exists
'r' | Source can be read
'w' | Source can be written
'x' | Source can be executed. This has no effect on Windows system (will behave like e).
pfs.stat(src[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.options<Object>sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
fs.Stats.
These functions return lstat information about a resource in the file system. Symbolic links are reported as links instead of followed targets.
pfs.chmod(src, mode[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.mode<Number> Is a numericbitmaskcreated using a logicalOR.options<Object>sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously changes the permissions of a file or directory tree.
import { bitmask } from 'pwd-fs';
await pfs.chmod('./path', 0o750);
const { mode } = await pfs.stat('./path');
console.log(bitmask(mode) === 0o750); // trueCaveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner or others is not implemented.
See manuals chmod(2)
pfs.chown(src[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.options<Object>- returns: <Promise> Resolves with
undefined.
Asynchronously changes owner and group of a file or directory tree.
If uid or gid is omitted, the current value is preserved. On Windows, chown() validates the path but does not change POSIX ownership.
See manuals chown(2).
pfs.symlink(src, dest[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.dest<String> Absolute or relative path to the symbolic link to create. Ifdestexists, it will not be overwritten.options<Object>sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously creates a new symbolic link (also known as a soft link).
await pfs.symlink('./path', './link');
const stats = await pfs.stat('./link');
console.log(stats.isSymbolicLink()); // trueSee manuals symlink(2).
pfs.copy(src, dir[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.dir<String> Absolute or relative path to the directory to which the resource is to be copied.options<Object>umask<Number> Umask or file mode creation mask is a grouping of bits, each of which restricts how its corresponding permission is set for newly created files or directories. See manuals umask(2). Not supported on Windows system. Default:0o000.overwrite<Boolean> Replace an existing target before copying. Default:false.filter<Function> Optional(src, dest) => booleanpredicate. Returnfalseto skip a resource.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously copies a file or directory recursively into dir. The destination directory must exist. The created target is path.join(dir, path.basename(src)).
import { pfs } from 'pwd-fs';
await pfs.mkdir('./dist');
await pfs.copy('./path/file.txt', './dist');pfs.rename(src, dest[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.dest<String> Absolute or relative destination path in the file system.options<Object>sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Rename file or directory. See manuals rename(2).
await pfs.rename('./path/old_name.txt', './path/new_name.txt');pfs.remove(src[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.options<Object>sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously removes a file or directory recursively. Missing paths reject or throw, matching fs.rm(..., { force: false }).
pfs.emptyDir(src[, options])
src<String> Absolute or relative path to the directory in the file system. Relative paths are resolved againstpfs.pwd.options<Object>sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously removes all entries inside a directory while preserving the directory itself.
await pfs.emptyDir('./cache');pfs.read(src[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.options<Object>encoding<String> | <null> Is the expected string encoding. Default:'utf8'.flag<String> See support of file system flags. Default:'r'.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with a
string. Ifencodingis <null>, the data is returned as a <Buffer> object.
Asynchronously reads the entire contents of a file.
const content = await pfs.read('./file.txt');
console.log(content); // 'Lorem Ipsum...'pfs.write(src, data[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.data<String> | <Buffer>options<Object>umask<Number> Umask or file mode creation mask is a grouping of bits, each of which restricts how its corresponding permission is set for newly created files or directories. See manuals umask(2). Not supported on Windows system. Default:0o000.encoding<String> Is the expected string encoding. Default:'utf8'.flag<String> See support of file system flags. Default:'w'.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously writes data to a file, replacing the file if it already exists. If the file does not exist, a new file is created.
The encoding option is ignored if data is a buffer.
await pfs.write('./file.txt', '... some text');For
stream,fs.createWriteStream()is recommended.
pfs.append(src, data[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.data<String> | <Buffer>options<Object>umask<Number> Umask or file mode creation mask is a grouping of bits, each of which restricts how its corresponding permission is set for newly created files or directories. See manuals umask(2). Not supported on Windows system. Default:0o000.encoding<String> Is the expected string encoding. Default:'utf8'.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Asynchronously appends data to a file, creating the file if it does not yet exist.
NOTE Method is deprecated. May be removed in the next major version
Use instead pfs.write(src, data[, options]) with { flag: 'a' } option
await pfs.write('./file', 'some content', {
flag: 'a'
});pfs.readdir(dir[, options])
dir<String> Absolute or relative path to the directory you want to read.options<Object>encoding<String> | <null> Is the expected string encoding. Default:'utf8'.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with an
Arrayof file names in the directory excluding'.'and'..'. Ifencodingis <null>, entries are returned as <Buffer> objects. Otherwise, entries are strings.
Asynchronously reads the contents of a directory. Returns an empty Array if the directory is empty. See manuals readdir(3).
const list = await pfs.readdir('./files');
console.log(list); // ["icons", "logo.svg"]pfs.readlink(src[, options])
src<String> Absolute or relative path to the symbolic link in the file system. Relative paths are resolved againstpfs.pwd.options<Object>encoding<String> Is the expected string encoding. Default:'utf8'.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with a
string.
Asynchronously reads the path stored in a symbolic link.
const target = await pfs.readlink('./current');
console.log(target); // "./releases/current"pfs.realpath(src[, options])
src<String> Absolute or relative path to the resource in the file system. Relative paths are resolved againstpfs.pwd.options<Object>encoding<String> Is the expected string encoding. Default:'utf8'.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with a
string.
Asynchronously resolves a path to its canonical absolute location.
const realpath = await pfs.realpath('./current');
console.log(realpath); // "/absolute/path/to/releases/current"pfs.mkdir(dir[, options])
dir<String> Absolute or relative path to the directory you want to create.options<Object>umask<Number> Umask or file mode creation mask is a grouping of bits, each of which restricts how its corresponding permission is set for newly created files or directories. See manuals umask(2). Not supported on Windows system. Default:0o000.sync<Boolean> Synchronous execution. Default:false.
- returns: <Promise> Resolves with
undefined.
Recursively creates directories. Resolves successfully if the directory already exists.
await pfs.mkdir('./static/images');pfs.pwd
- <String>
The full path from the root directory to the working directory: in the context of which relative paths will be resolved.
static: bitmask(mode)
Masking is the act of applying a mask to a value. Bitwise ANDing in order to extract a subset of the bits in the value.
import { bitmask } from 'pwd-fs';
// Access: (0644/-rw-r--r--)
const { mode } = await pfs.stat('./things.txt');
const access = bitmask(mode);
console.log(access === 0o644); // trueApplying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
mode: 33188
mask: 0o644 (rw-rw-r--)Mode creation mask
The following table shows some examples of how to set the extension mode or umask for files and directories.
| Umask | Mode files | Mode directories | |-------|-------------------|-------------------| | 0o000 | 0o666 (rw-rw-rw-) | 0o777 (rwxrwxrwx) | | 0o002 | 0o664 (rw-rw-r--) | 0o775 (rwxrwxr-x) | | 0o007 | 0o660 (rw-rw----) | 0o770 (rwxrwx---) | | 0o022 | 0o644 (rw-r--r--) | 0o755 (rwxr-xr-x) | | 0o027 | 0o640 (rw-r-----) | 0o750 (rwxr-x---) | | 0o077 | 0o600 (rw-------) | 0o700 (rwx------) | | 0o277 | 0o400 (r--------) | 0o500 (r-x------) |
String encoding
The following encodings are available wherever the encoding option takes a <String>.
Encoding | Description
---------|------------
'ascii' | Each alphabetic, numeric or special character is represented by a 7-bit binary number (a string of seven 0 or 1), which is assigned a number from 0 to 127.
'base64' | Three 8-bit bytes (i.e., a total of 24 bits) can be represented by four 6-bit digits. The full specification of this form is contained in IANA RFC 1421 and RFC 2045.
'hex' | Encode each byte as two hexadecimal characters.
'ucs2' | 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.
'utf16le' | Like 'ucs2.
'utf8' | Multibyte encoded Unicode characters. The first 128 characters of Unicode, which correspond one-to-one with ascii, are encoded using a single octet with the same binary value as ascii, so that valid ascii text is valid utf8-encoded Unicode as well.
'latin1' | Defined by the IANA in RFC1345, only in node 6.4.0+.
'binary' | Like 'latin1.
File system flags
The following flags are available for pfs.read and pfs.write the flag option takes a <String>.
Flag | Description
-----|------------
'a' | Open file for appending. The file is created if it does not exist.
'ax' | Like 'a' but fails if the path exists.
'a+' | Open file for reading and appending. The file is created if it does not exist.
'ax+' | Like 'a+' but fails if the path exists.
'as' | Open file for appending in synchronous mode. The file is created if it does not exist.
'as+' | Open file for reading and appending in synchronous mode. The file is created if it does not exist.
'r' | Open file for reading. Fails if the file does not exist.
'r+' | Open file for reading and writing. Fails if the file does not exist.
'rs+' | Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. Using this flag is not recommended unless it is needed.
'w'| Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
'wx' | Like 'w' but fails if the path exists.
'w+' | Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
'wx+' | Like 'w+' but fails if the path exists.
The behavior of some flags is platform-specific.
When To Use Native fs
Prefer native node:fs APIs directly when you need:
- streams such as
createReadStream()orcreateWriteStream() - advanced flags and options not exposed by this wrapper
- very low-level control over file descriptors
- exact parity with Node's callback-based APIs
