> 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.

# Getting started with Node.js

## Requirements

Node.js 18 or later. The [WebAssembly build](https://anyformat.swc.rs/guide/node/webassembly.md) needs Node.js
20.19, 22.13, 23.5, or later.

## Install a package

Install the package of each format family that you use. The examples on this
page use the image family.


```sh [npm]
npm add @swc/anyformat-image
```

```sh [yarn]
yarn add @swc/anyformat-image
```

```sh [pnpm]
pnpm add @swc/anyformat-image
```

```sh [bun]
bun add @swc/anyformat-image
```

```sh [deno]
deno add npm:@swc/anyformat-image
```

## Detect the format of a file

Give the bytes of a file to `detect`. The function needs only the first bytes of
the file. 64 bytes are enough for most image files.

```js
import { readFile } from 'node:fs/promises'
import { detect } from '@swc/anyformat-image'

await detect(await readFile('photo.avif'))
// => { format: 'avif', mimeType: 'image/avif' }
```

When the format is not recognized, `detect` returns `null`. `detect` returns a
promise and does the work on the libuv thread pool. `detectSync` is the
synchronous form.

## List the supported formats

`supportedFormats` returns the identifier of each format that `detect` can
return.

```js
import { supportedFormats } from '@swc/anyformat-image'

supportedFormats()
// => ['png', 'jpeg', 'gif', 'webp', 'avif', 'heic', 'jxl', 'tiff', 'bmp', 'ico', 'qoi']
```

## Compare two images

`compareImages` decodes two PNG files, compares them with the algorithm of
pixelmatch, and encodes the diff image.

```js
import { readFile, writeFile } from 'node:fs/promises'
import { compareImages } from '@swc/anyformat-image'

const result = await compareImages(
  await readFile('expected.png'),
  await readFile('actual.png'),
  { threshold: 0.1, diff: { format: 'png' } },
)
if (result.diffPixels > 0) await writeFile('diff.png', result.diffEncoded)
```

## Next steps

- Read the [API reference](https://anyformat.swc.rs/api.md) of each format family.
- If no native addon can load in your environment, read
  [WebAssembly build](https://anyformat.swc.rs/guide/node/webassembly.md).
- If you use pngjs and pixelmatch, read
  [Migrate from pngjs and pixelmatch](https://anyformat.swc.rs/guide/node/migrate-from-pngjs-and-pixelmatch.md).
- If you use ssim.js, read [Migrate from ssim.js](https://anyformat.swc.rs/guide/node/migrate-from-ssim-js.md).
- Read [Development](https://anyformat.swc.rs/guide/development.md) to build anyformat from source.
