Skip to content

Commit

Permalink
adopted original formatting, added readme entry for how to append cus…
Browse files Browse the repository at this point in the history
…tom fields.
  • Loading branch information
lukas committed Feb 6, 2022
1 parent af10d08 commit 2e89215
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 26 deletions.
27 changes: 27 additions & 0 deletions README.md
Expand Up @@ -164,6 +164,33 @@ photos
}
```

## Adding custom fields
You can easily extend a `DirectoryTree` object with custom fields by adding them to the custom field.
For example add an `id` based on the path of a `DirectoryTree` object for each directory and file like so:
```
import { createHash } from 'crypto';
import * as directoryTree from 'directory-tree';
import { DirectoryTree, DirectoryTreeOptions, DirectoryTreeCallback } from 'directory-tree';
const callback: DirectoryTreeCallback = (
item: DirectoryTree,
path: string
) => {
item.custom.id = createHash('sha1').update(path).digest('base64');
};
const dirTree: DirectoryTree & { id?: string } = directoryTree(
"<your-directory-path>",
{},
callback,
callback
);
// to explore the object with the new custom fields
console.log(JSON.stringify(dirTree, null, 2));
```

## Note

Device, FIFO and socket files are ignored.
Expand Down
48 changes: 22 additions & 26 deletions index.d.ts
@@ -1,37 +1,33 @@
import { Stats } from 'fs';

declare function directoryTree(
path: string,
options?: directoryTree.DirectoryTreeOptions,
onEachFile?: directoryTree.DirectoryTreeCallback,
onEachDirectory?: directoryTree.DirectoryTreeCallback
path: string,
options ? : directoryTree.DirectoryTreeOptions,
onEachFile ? : directoryTree.DirectoryTreeCallback,
onEachDirectory ? : directoryTree.DirectoryTreeCallback,
): directoryTree.DirectoryTree;

export as namespace directoryTree;

declare namespace directoryTree {
export interface DirectoryTree {
path: string;
name: string;
size: number;
type: 'directory' | 'file';
children?: DirectoryTree[];
extension?: string;
isSymbolicLink?: boolean;
custom: { [key: string]: any };
}
export interface DirectoryTreeOptions {
normalizePath?: boolean;
exclude?: RegExp | RegExp[];
attributes?: (keyof Stats | 'type' | 'extension')[];
extensions?: RegExp;
followSymlink?: boolean;
}
export type DirectoryTreeCallback = (
item: DirectoryTree,
path: string,
stats: Stats
) => void;
export interface DirectoryTree {
path: string;
name: string;
size: number;
type: "directory" | "file";
children ? : DirectoryTree[];
extension?: string;
isSymbolicLink?: boolean;
custom: { [key: string]: any };
}
export interface DirectoryTreeOptions {
normalizePath ? : boolean;
exclude ? : RegExp | RegExp[];
attributes ? : (keyof Stats | "type" | "extension")[];
extensions ? : RegExp;
followSymlink ? : boolean;
}
export type DirectoryTreeCallback = (item: DirectoryTree, path: string, stats: Stats) => void;
}

export = directoryTree;

0 comments on commit 2e89215

Please sign in to comment.