For AI agents: the complete documentation index is available at https://anyformat.swc.rs/llms.txt, the full documentation bundle is available at https://anyformat.swc.rs/llms-full.txt, and this page is available as Markdown at https://anyformat.swc.rs/api/anyformat.md.

Any format

The @swc/anyformat (Node.js) and anyformat-core (Python) packages identify the format of a file of any family. Use them when a file can be of any family, for example a file that a user uploads. They replace file-type in Node.js, and python-magic (which needs libmagic) or filetype in Python, for the formats that anyformat supports.

LanguagePackageModule
Node.js@swc/anyformat@swc/anyformat
Pythonanyformat-coreanyformat_core

The package contains the detection code of every family and nothing else. To decode, encode, or compare files, install the package of the family, for example @swc/anyformat-image.

Supported formats

detect returns these formats. The first extension of each format is the most common one.

FamilyIdentifierMIME typeExtensions
Imagepngimage/pngpng
Imagejpegimage/jpegjpg, jpeg
Imagegifimage/gifgif
Imagewebpimage/webpwebp
Imageavifimage/avifavif
Imageheicimage/heicheic, heif
Imagejxlimage/jxljxl
Imagetiffimage/tifftiff, tif
Imagebmpimage/bmpbmp
Imageicoimage/vnd.microsoft.iconico
Imageqoiimage/qoiqoi
Videomp4video/mp4mp4, m4v
Videomovvideo/quicktimemov, qt
Video3gpvideo/3gpp3gp, 3g2
Videowebmvideo/webmwebm
Videomkvvideo/x-matroskamkv
Videoavivideo/x-msvideoavi
Videoflvvideo/x-flvflv
Videotsvideo/mp2tts, m2ts, mts
Videompgvideo/mpegmpg, mpeg
Audiomp3audio/mpegmp3
Audioaacaudio/aacaac
Audiom4aaudio/mp4m4a, m4b
Audioflacaudio/flacflac
Audiowavaudio/wavwav
Audioaiffaudio/aiffaiff, aif, aifc
Audioopusaudio/opusopus
Audiooggaudio/oggogg, oga
Audiomidiaudio/midimid, midi
Audioamraudio/amramr
Fontttffont/ttfttf
Fontotffont/otfotf
Fontttcfont/collectionttc
Fontwofffont/woffwoff
Fontwoff2font/woff2woff2
Fonteotapplication/vnd.ms-fontobjecteot
PDFpdfapplication/pdfpdf
Officedocxapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentdocx
Officexlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetxlsx
Officepptxapplication/vnd.openxmlformats-officedocument.presentationml.presentationpptx
Officeodtapplication/vnd.oasis.opendocument.textodt
Officeodsapplication/vnd.oasis.opendocument.spreadsheetods
Officeodpapplication/vnd.oasis.opendocument.presentationodp
Officecfbapplication/x-cfbdoc, xls, ppt
Officertfapplication/rtfrtf

How detect works

detect tries the detect function of each family in this order and returns the first match: image, video, audio, font, PDF, office. The family packages use the same detection code. For PDF files, detect uses the same check as isPdf of the PDF family.

Some container formats belong to more than one family. For example, an ISO BMFF file is an image (AVIF, HEIC), a video (MP4, MOV, 3GP), or audio (M4A). The ftyp brands of the file select the family, and the brands of the families do not overlap. The order makes the result stable if two families match the same file in a later version.

detect reads only the leading bytes of a file and does not check the rest of the file:

  • Most formats need at most the first 1032 bytes, because a PDF header can start anywhere in the first 1024 bytes.
  • ZIP-based office documents need the local file headers up to the entry that identifies the format. This is usually in the first few kilobytes.
  • An audio file with an ID3v2 tag needs the whole tag and a few bytes after it.

detectPrefixLenSync tells how many leading bytes detect needs for a file. detectFile and detectStream read only these bytes.

detect

Identifies the format of data from its leading bytes. Returns null in Node.js and None in Python when the format is not recognized.

families limits the detection to these families. The function tries them in the order above, not in the order of families. An empty list matches no file. An unknown family name is an error: ERR_INVALID_ARG_VALUE in Node.js and ValueError in Python.

Node.js

type Family = 'image' | 'audio' | 'video' | 'font' | 'pdf' | 'office'

function detect(
  data: Uint8Array,
  options?: { families?: readonly Family[] | null } | null,
): Promise<DetectedFile | null>
function detectSync(
  data: Uint8Array,
  options?: { families?: readonly Family[] | null } | null,
): DetectedFile | null
import { readFile } from 'node:fs/promises'
import { detect } from '@swc/anyformat'

await detect(await readFile('photo.jpg'))
// => { family: 'image', format: 'jpeg', mimeType: 'image/jpeg', extensions: ['jpg', 'jpeg'] }

await detect(await readFile('photo.jpg'), { families: ['audio', 'video'] })
// => null

detect detects the format on the libuv thread pool. It copies only the leading bytes that the families need, so you can change data after the call. detectSync blocks the event loop. An argument of a wrong type rejects the promise of detect and makes detectSync throw.

Python

Family = Literal["image", "audio", "video", "font", "pdf", "office"]

def detect(data: Buffer, *, families: Sequence[Family] | None = None) -> DetectedFile | None

data is bytes or any other object with the buffer protocol, for example bytearray or memoryview.

from pathlib import Path

import anyformat_core

anyformat_core.detect(Path("photo.jpg").read_bytes())
# => DetectedFile(family='image', format='jpeg', mime_type='image/jpeg', extensions=('jpg', 'jpeg'))

anyformat_core.detect(Path("photo.jpg").read_bytes(), families=["audio", "video"])
# => None

detectFile

Identifies the format of the file at path. The function reads only the leading bytes that detectPrefixLenSync asks for, not the whole file. The result is the same as the result of detect on the bytes of the file, with the same families option. Returns null in Node.js and None in Python when the format is not recognized.

Node.js

function detectFile(
  path: string | URL,
  options?: { families?: readonly Family[] | null } | null,
): Promise<DetectedFile | null>
function detectFileSync(
  path: string | URL,
  options?: { families?: readonly Family[] | null } | null,
): DetectedFile | null
import { detectFile } from '@swc/anyformat'

await detectFile('upload.bin')
// => { family: 'image', format: 'jpeg', mimeType: 'image/jpeg', extensions: ['jpg', 'jpeg'] }

await detectFile('upload.bin', { families: ['audio', 'video'] })
// => null

detectFile reads the file and detects the format on the libuv thread pool. detectFileSync blocks the event loop. A URL must use the file: scheme.

When the file cannot be read, detectFile rejects, and detectFileSync throws, an Error with these properties:

  • code: the Node.js errno name, for example ENOENT, EACCES, or EISDIR, or ERR_IO for an error that has no errno name.
  • path: the path of the file.

Python

def detect_file(
    path: str | os.PathLike[str], *, families: Sequence[Family] | None = None
) -> DetectedFile | None
import anyformat_core

anyformat_core.detect_file("upload.bin")
# => DetectedFile(family='image', format='jpeg', mime_type='image/jpeg', extensions=('jpg', 'jpeg'))

The function releases the GIL while it reads the file. When the file cannot be read, it raises the OSError subclass of the error, as open does, for example FileNotFoundError, PermissionError, or IsADirectoryError. The filename attribute of the exception is path.

detectStream

Identifies the format of a stream, for example an upload or an HTTP response. The function reads only the leading bytes that detectPrefixLenSync asks for. The families option is the same as the option of detect. With fewer families, the function can read fewer bytes.

Node.js

function detectStream(
  stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>,
  options?: { families?: readonly Family[] | null } | null,
): Promise<{ result: DetectedFile | null; stream: ReadableStream<Uint8Array> }>
import { detectStream } from '@swc/anyformat'

const response = await fetch('https://example.com/file')
const { result, stream } = await detectStream(response.body)
// result => { family: 'pdf', format: 'pdf', mimeType: 'application/pdf', extensions: ['pdf'] }
// stream gives all of the bytes of the response.

The function reads chunks until it has the bytes that detectPrefixLenSync asks for, or until the input ends. Then it calls detectSync. The returned stream gives all of the bytes of the input, including the bytes that the function read, so use the returned stream and not the input stream. The input can be a web ReadableStream or an async iterable, for example a Node.js Readable. Each chunk must be a Uint8Array, for example a Buffer.

Python

def detect_stream(
    f: BinaryIO, *, families: Sequence[Family] | None = None
) -> DetectedFile | None
import anyformat_core

with open("upload.bin", "rb") as f:
    anyformat_core.detect_stream(f)
    # => DetectedFile(family='image', format='jpeg', mime_type='image/jpeg', extensions=('jpg', 'jpeg'))
    # f.tell() is the same as before the call.

f must be a seekable binary file object. The function records f.tell(), reads the bytes that detect_prefix_len asks for, and seeks back to the recorded position. When f.seekable() is false, the function raises io.UnsupportedOperation. For such an object, read a prefix with detect_prefix_len and call detect:

data = b""
while len(data) < anyformat_core.detect_prefix_len(data):
    chunk = f.read(anyformat_core.detect_prefix_len(data) - len(data))
    if not chunk:
        break
    data += chunk
anyformat_core.detect(data)

detectPrefixLenSync

Returns the number of leading bytes that detect needs to give its final result for data, the bytes read so far. The value is the largest value of detectPrefixLenSync of the families in families. It can grow when more bytes are available, for example for an ID3v2 tag. The maximum value is 16 MiB. When families is empty, the value is 0.

detectFile and detectStream read the bytes that this function asks for. Use it to read a prefix yourself.

Node.js

function detectPrefixLenSync(
  data: Uint8Array,
  options?: { families?: readonly Family[] | null } | null,
): number

Python

def detect_prefix_len(data: Buffer, *, families: Sequence[Family] | None = None) -> int

DetectedFile

A file format identified by detect, with its family.

Node.jsPythonTypeDescription
familyfamilyFamilyThe family of the format.
formatformatstringThe identifier of the format in its family, for example "png". It is the same as format of detect of the family. For PDF files, it is "pdf".
mimeTypemime_typestringThe most common MIME type of the format.
extensionsextensionsstring[]The usual file extensions of the format, without a dot, for example ["jpg", "jpeg"]. The first extension is the most common one.

Use extensions to check that the name of a file matches its content.

In Python, DetectedFile is a final class with read-only properties. The type of extensions is tuple[str, ...], and the type of the other properties is str. Two objects with the same values are equal.

supportedFormats

Every format that detect can return, grouped by family in the order that detect tries the families. It contains every format of supportedFormats of each family, and PDF. In Node.js, the array and its objects are frozen. In Python, the constant is SUPPORTED_FORMATS, a tuple of DetectedFile.

Node.js

const supportedFormats: readonly Readonly<DetectedFile>[]
import { supportedFormats } from '@swc/anyformat'

supportedFormats.filter((format) => format.family === 'font').map((format) => format.format)
// => ['ttf', 'otf', 'ttc', 'woff', 'woff2', 'eot']

Python

SUPPORTED_FORMATS: tuple[DetectedFile, ...]
import anyformat_core

[format.format for format in anyformat_core.SUPPORTED_FORMATS if format.family == "font"]
# => ['ttf', 'otf', 'ttc', 'woff', 'woff2', 'eot']