File system helpers
npm install @neodx/fsFile system enhancements and common stuff.
APIs overview:
- scan(path, ['.js', '.module.ts', '!*.test.{ts,js}']) - glob reader with multiple inputs supportensureDir(path)
- , ensureFile(path) - Safe file/dir creation with all required ancestorsexists(path)
- , isFile(path), isDirectory(path) - Safe path checksdeepReadDir(path)
- - Deep version of readdirparseJson(input)
- , serializeJson(input) - Safe JSON parser and serializer with JSONC supportgetFileHash(path)
- , getHash(content) - Returns file hash based on its content (HEX)
Glob-based (via tiny-glob) multiple patterns scanner with exclusion support
`typescript
import { scan } from '@neodx/fs';
await scan(process.cwd(), ['.js', '!.config.js']);
await scan(process.cwd(), '/.ts', '/.js');
`
Recursively creates missed file or dir with all required ancestors if one of them is not exists.
Automatically avoid duplicated calls:
`typescript
import { ensureFile, ensureDir } from '@neodx/fs';
// Everything works as expected
await Promise.all([
ensureDir('foo/baz'),
ensureFile('foo/bar/2.ts'),
ensureDir('foo/bar'),
ensureFile('foo/bar/1.ts'),
ensureDir('foo')
]);
`
The following APIs are useful for safe paths checking.
- exists(path) - Returns true if the path existsisFile(path)
- - Returns true if the path exists, and it's a fileisDirectory(path)
- - Returns true if the path exists, and it's a directory
Returns flat list with all children's paths. Paths are relative by default.
`typescript
import { deepReadDir, isFile } from '@neodx/fs';
const files = await deepReadDir(myPath);
for (const file of files) {
if (await isFile(file)) {
await doSmth(file);
}
}
`
`typescript
import { parseJson, serializeJson } from '@neodx/fs';
import { writeFile, readFile } from 'fs/promises';
const json = parseJson(await readFile('tsconfig.json', 'utf-8'));
await writeFile(
'tsconfig.json',
serializeJson({
...json,
compilerOptions: {
...json.compilerOptions,
target: 'esnext'
}
}),
'utf-8'
);
``
---
Inspired by fs-extra and others.