Pathy
Whether you're trying to normalize between POSIX-style and Windows-style separators, sort a bunch of path strings in a useful way, or easily find or read files... working with file paths is a huge pain.
This package provides a single main export, the Pathy
class, which is an immutable instance representing a path and providing a bunch of useful methods for common path and file operations.
Requirements
Installation
Install from npm, via your package manager of choice.
For example: npm install @bscotch/path
or pnpm add @bscotch/path
Usage
import {pathy, Pathy} from '@bscotch/pathy';
const myDir = pathy("my/directory");
const myFiles = await myDir.listChildrenRecursively();
const myFilesAsStrings = await myDir.listChildrenRecursively({
transform(path){
return path.absolute;
}
});
const myConfigPath = myDir.join("config.yaml");
const myConfigPathAsJson = myConfigPath.changeExtension('json');
const myDirAgain = myConfigPath.up();
const myConfig = await myConfigPath.read();
myConfig.someField = "a new value!";
await myConfigPath.write(myConfig);
import {z} from 'zod';
const myConfigValidator = z.object({someField: z.string().default('whatever')});
const myTypedConfigPath = myConfigPath.withValidator(myConfigValidator);
const myParsedConfigUnlessError = await myTypedConfigPath.read();
await myTypedConfigPath.write({someField: 100});
await myDir.isFile();
await myDir.isDirectory();
myDir.isRoot;
myDir.hasExtension('png');
myDir.hasExtension('.png');
myDir.isParentOf(myConfigPath);
await myDir.exists();
await myDir.isEmptyDirectory();
await myDir.listSiblings();
myDir.equals('some\\other\\dir');
const packageJsonPath = await myDir.findInParents("package.json");
await myDir.ensureDirectory();
await myDir.copy('some/other/dir');
await myDir.delete();
const myPathString = `${myDir}`;
const myWindowsRelativePathString = myDir.toString({relative:true, format: 'win32'});
const jsonStringified = JSON.stringify({myDir, yep:true});
Pathy.explode("my/path");
Pathy.lineage("/my/whole/path");
['my/path/1', 'my/path','mypath'].sort(Pathy.compare);