Skip to content

fb.library media library

For full-library enumeration, prefer getCount() plus paged getAll(start, count), or use enumerateTracks(). Use getRoots() for real library roots, browseTree() for typed directory browsing, and enumerateTree() for high-level traversal. browseDirectory() and enumerateDirectories() are deprecated legacy projection APIs.

search(query, limit?)

Searches the media library and returns a LibrarySearchResponse.

ParameterTypeDescription
querystringfoobar2000 query expression
limitnumber?Maximum result count
optionsOmit<LibrarySearchParams, 'query' | 'limit'>?Additional native search options

tracks and the compatibility alias items contain track rows. hasMore indicates that more matching rows exist.

javascript
const results = await fb.library.search('artist HAS Beatles', 100);
console.log(`Found ${results.total} tracks`);
if (results.hasMore) console.log('More results are available');

getAlbums(limit?)

Returns album aggregates. Pass either a numeric limit or a LibraryGetAlbumsParams object.

javascript
const albums = await fb.library.getAlbums(50);
// { albums: [{ name, artist, trackCount, duration, ... }], total, offset, limit, hasMore }

getArtists(limit?)

Returns artist aggregates.

ParameterTypeDescription
limitnumber?Maximum result count
optionsOmit<LibraryGetArtistsParams, 'limit'>?Additional native options
javascript
const artists = await fb.library.getArtists(100);

getStats()

Returns aggregate statistics such as totalTracks, totalAlbums, totalArtists, totalDuration, and totalSize.

javascript
const stats = await fb.library.getStats();
console.log(`${stats.totalTracks} tracks, ${stats.totalDuration} seconds`);

getGenres()

Returns { success, genres: [{ name, trackCount }] }.

javascript
const r = await fb.library.getGenres();
// {genres: [{name: 'Rock', trackCount: 5000}, ...]}

getStatus()

Returns media-library state, including initialized and optional enabled, scanning, itemCount, and count fields.

javascript
const s = await fb.library.getStatus();
if (s.initialized) console.log('The library is initialized');

getCount()

Returns the media-library item count as { count }.

javascript
const { count } = await fb.library.getCount();

getAll(start, count)

Returns paged tracks as LibraryPagedTracksResponse. When the host offloads a full-library request to a background worker, the wrapper waits for the matching library:getAllResult event and still resolves to the same final shape.

ParameterTypeDescription
startnumber?Start offset
countnumber?Maximum result count
opts.timeoutnumber?Client-side timeout in milliseconds; defaults to 60000, and 0 disables it
javascript
const r = await fb.library.getAll(0, 100);
console.log(`${r.total} total tracks; received ${r.tracks.length}`);

items is a compatibility alias that normally contains the same rows as tracks.

enumerateTracks(options?)

This high-level async generator pages through the library and supports pageSize, start, useCache, signal, and onProgress.

javascript
for await (const page of fb.library.enumerateTracks({ pageSize: 500 })) {
  console.log(page.fetched, '/', page.total);
}

refresh()

Requests a library refresh and returns a BaseResponse.

getByPath(path)

Looks up a library item by path. Metadata fields are returned at the top level when found is true.

javascript
const r = await fb.library.getByPath('E:\\\\Music\\\\song.flac');
if (r.found) console.log(r.title, r.artist);

getRoots()

Returns resolved media-library roots.

javascript
const { roots, total, indexedTracks } = await fb.library.getRoots();
for (const root of roots) {
  console.log(root.displayName, root.absolutePath, root.trackCount);
}
Response fieldTypeDescription
rootsLibraryRootInfo[]Resolved root descriptors
totalnumberRoot count
indexedTracksnumberSuccessfully indexed items
skippedTracksnumberItems not assigned to a stable local root
enabledbooleanWhether the media library is enabled
fromCachebooleanWhether the result came from cache
Root fieldTypeDescription
idstringStable identifier; currently the canonical absolutePath
displayNamestringHuman-readable root name
rawPathstringCurrently identical to absolutePath
absolutePathstringCanonical local absolute path
trackCountnumberTracks below this root

Only items that resolve to stable local absolute paths contribute roots. Protocol-backed items such as http://, file-relative://, and unpack:// contribute to skippedTracks. The first call builds the index; later calls may use the cache, which is invalidated by library changes or invalidateCache().

browseTree(params)

Browses the typed directory tree using rootId and optional pathId. Call getRoots() first to obtain a valid root ID.

javascript
const { roots } = await fb.library.getRoots();
const tree = await fb.library.browseTree({ rootId: roots[0].id });
for (const dir of tree.directories) {
  console.log(dir.name, dir.trackCount, dir.hasChildren);
}
// Expand a child and include its direct files.
const sub = await fb.library.browseTree({
  rootId: roots[0].id,
  pathId: tree.directories[0].pathId,
  includeFiles: true
});
ParameterTypeRequiredDescription
rootIdstringYesRoot ID from getRoots().roots[].id
pathIdstringNoSlash-separated path below the root; defaults to ""
includeFilesbooleanNoInclude files; defaults to false
recursiveFilesbooleanNoInclude descendant files recursively when files are enabled
Response fieldTypeDescription
rootLibraryRootInfoOwning root
pathIdstringRequested path ID
absolutePathstringCurrent absolute directory path
directoriesLibraryDirectoryNodeInfo[]Immediate child directories
filesTrackInfo[]Files; empty when includeFiles is false
fromCachebooleanWhether the result came from cache

The host reports "rootId is required", "Unknown rootId", or "Path not found" for the corresponding invalid requests.

enumerateTree(options)

Root-aware async generator that performs breadth-first or depth-first traversal through browseTree().

javascript
for await (const batch of fb.library.enumerateTree({
  rootId: roots[0].id,
  strategy: 'bfs',
  includeFiles: true
})) {
  console.log(batch.pathId, batch.directories.length, batch.files.length);
  console.log(`${batch.visited} visited, ${batch.pending} pending`);
}
ParameterTypeRequiredDescription
rootIdstringYesRoot ID from getRoots()
pathIdstringNoStarting path; defaults to the root
includeFilesbooleanNoInclude direct files; defaults to false
strategy'bfs' | 'dfs'NoTraversal strategy; defaults to 'bfs'
signalAbortSignalNoCooperative cancellation signal
onProgressFunctionNoReceives { rootId, pathId, absolutePath, visited, pending }
Yielded fieldTypeDescription
...browseTreeResponse-Includes root, pathId, absolutePath, directories, files, and fromCache
visitednumberNodes visited
pendingnumberNodes still queued
Final return fieldTypeDescription
rootIdstringTraversed root ID
visitednumberTotal nodes visited
abortedbooleanWhether the signal aborted traversal

Each yielded batch corresponds to a browseTree({ recursiveFiles: false }) call, so files contains only the current node's direct files.

browseDirectory(path, includeFiles?)

Deprecated legacy projection API. Prefer getRoots(), browseTree(), and enumerateTree().

Returns legacy directory strings and optional track rows.

An empty path means the projected top-level view; it is not the configured foobar2000 root list.

javascript
const root = await fb.library.browseDirectory('', false);

enumerateDirectories(options?)

Deprecated legacy async generator built on browseDirectory(). Use the typed root APIs for real roots.

Supports breadth-first and depth-first traversal of the legacy projection.

javascript
for await (const node of fb.library.enumerateDirectories({ rootPath: '', strategy: 'bfs' })) {
  console.log(node.path, node.directories.length);
}

getAlbumTracks(album, artist?)

Returns matching album tracks.

javascript
const tracks = await fb.library.getAlbumTracks('Abbey Road', 'The Beatles');

getFieldValues(field, limit?, separator?)

Returns distinct values and track counts for a metadata field. enumerateFieldValues(field, options?) is a semantic alias that accepts { limit?, separator? }.

javascript
const years = await fb.library.getFieldValues('date', 50);
const moreYears = await fb.library.enumerateFieldValues('date', { limit: 50 });

query(query, sort?, limit?)

Runs a foobar2000 query with an optional Title Formatting sort expression.

javascript
const r = await fb.library.query('%rating% GREATER 3', '%rating%', 100);

Supplemental method reference

addToPlaylist(paths, playlistIndex?)

Signature: fb.library.addToPlaylist(paths: string[], playlistIndex?: number): Promise<LibraryAddToPlaylistResponse>

ParameterTypeRequiredDescription
pathsstring[]YesTrack paths to append
playlistIndexnumberNoTarget playlist; omitted for the host default

Returns the append result, including optional added metadata.

javascript
await fb.library.addToPlaylist(['E:\\Music\\song.flac'], 0);

getArtistAlbums(artist, limit?)

Signature: fb.library.getArtistAlbums(artist: string, limit?: number): Promise<{ albums: AlbumInfo[] }>

ParameterTypeRequiredDescription
artiststringYesArtist name
limitnumberNoMaximum result count

Returns the artist's album aggregates.

javascript
const albums = await fb.library.getArtistAlbums('The Beatles', 50);

getArtistTracks(artist, limit?)

Signature: fb.library.getArtistTracks(artist: string, limit?: number): Promise<LibraryArtistTracksResponse>

ParameterTypeRequiredDescription
artiststringYesArtist name
limitnumberNoMaximum result count

Returns matching tracks plus artist and count metadata.

javascript
const tracks = await fb.library.getArtistTracks('The Beatles', 100);

getCacheStats()

Signature: fb.library.getCacheStats(): Promise<LibraryCacheStatsResponse>

ParameterTypeRequiredDescription
---No parameters

Returns the extensible library-cache statistics envelope.

javascript
const cache = await fb.library.getCacheStats();

getRandomTracks(count?)

Signature: fb.library.getRandomTracks(count?: number): Promise<LibraryRandomTracksResponse>

ParameterTypeRequiredDescription
countnumberNoNumber of random tracks

Returns { tracks, count } plus the base response fields.

javascript
const random = await fb.library.getRandomTracks(25);

getRecentlyAdded(limit?)

Signature: fb.library.getRecentlyAdded(limit?: number, sortBy?: string): Promise<LibraryRecentlyAddedResponse>

ParameterTypeRequiredDescription
limitnumberNoMaximum result count
sortBystringNoHost sort selector

Returns recently added tracks plus total, limit, sortBy, and fallback metadata.

javascript
const recent = await fb.library.getRecentlyAdded(50);

invalidateCache()

Signature: fb.library.invalidateCache(): Promise<LibraryInvalidateCacheResponse>

ParameterTypeRequiredDescription
---No parameters

Returns the invalidation result and optional timestamp.

javascript
await fb.library.invalidateCache();

isEnabled()

Signature: fb.library.isEnabled(): Promise<{ enabled: boolean }>

ParameterTypeRequiredDescription
---No parameters

Returns whether the media library is enabled.

javascript
const { enabled } = await fb.library.isEnabled();

refresh()

Signature: fb.library.refresh(): Promise<BaseResponse>

ParameterTypeRequiredDescription
---No parameters

Returns the refresh operation result.

javascript
await fb.library.refresh();

rescan()

Signature: fb.library.rescan(): Promise<BaseResponse>

ParameterTypeRequiredDescription
---No parameters

Returns the host rescan operation result.

javascript
await fb.library.rescan();