### Minimal Configuration Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Demonstrates a minimal configuration setup to extract only the EXIF tags from an image.
```javascript
const parser = exifParser.create(buffer)
.enableReturnTags(true)
.enableImageSize(false);
const result = parser.parse();
```
--------------------------------
### Browser Usage Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/START-HERE.md
Demonstrates how to use the exif-parser in a browser environment by including the script and parsing an ArrayBuffer.
```html
```
--------------------------------
### Install exif-parser
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Install the exif-parser package using npm. This is the primary method for adding the library to your Node.js project.
```bash
npm install exif-parser
```
--------------------------------
### Fluent Configuration Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/REFERENCE-OVERVIEW.md
Demonstrates how to chain configuration methods for the parser. All configuration methods return 'this' to allow for fluent chaining.
```javascript
const result = parser
.enableImageSize(true)
.enableReturnTags(true)
.enableSimpleValues(true)
.parse();
```
--------------------------------
### Raw Values Configuration Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Shows how to configure the parser to retrieve raw EXIF values without any simplification or type casting.
```javascript
const parser = exifParser.create(buffer)
.enableSimpleValues(false);
const result = parser.parse();
```
--------------------------------
### Full Configuration Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Illustrates a full configuration to extract all available information, including binary fields, pointers, tag names, image size, and simplified values.
```javascript
const parser = exifParser.create(buffer)
.enableBinaryFields(true)
.enablePointers(true)
.enableTagNames(true)
.enableImageSize(true)
.enableReturnTags(true)
.enableSimpleValues(true);
const result = parser.parse();
```
--------------------------------
### Tag Codes Configuration Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Demonstrates configuring the parser to use numerical tag codes instead of tag names in the output.
```javascript
const parser = exifParser.create(buffer)
.enableTagNames(false);
const result = parser.parse();
```
--------------------------------
### Mark and Branch Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/buffer-stream.md
Demonstrates creating a mark, reading data, calculating relative offset, and opening a new branch stream at a specific offset relative to the mark.
```javascript
const start = stream.mark();
// ... read some data ...
const relativeOffset = stream.offsetFrom(start);
const branch = start.openWithOffset(100);
```
--------------------------------
### Quickstart: Parse EXIF Metadata from an Image
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/START-HERE.md
This snippet demonstrates the basic workflow for parsing EXIF data from an image file. It covers creating a parser, configuring options like using tag names, parsing the buffer, and extracting common tags like camera make and model, image size, GPS coordinates, and thumbnails. Ensure 'photo.jpg' exists in the same directory.
```javascript
const exifParser = require('exif-parser');
const fs = require('fs');
// 1. Create a parser
const buffer = fs.readFileSync('photo.jpg');
const parser = exifParser.create(buffer);
// 2. Configure (optional - these are defaults)
parser.enableSimpleValues(true); // Cast to JS types
parser.enableTagNames(true); // Use tag names, not codes
// 3. Parse
const result = parser.parse();
// 4. Extract data
console.log(result.tags.Make); // Camera maker
console.log(result.tags.Model); // Camera model
console.log(result.getImageSize()); // {width: 3840, height: 2160}
// 5. Extract GPS (if available)
if (result.tags.GPSLatitude) {
console.log(` ${result.tags.GPSLatitude}, ${result.tags.GPSLongitude}`);
}
// 6. Extract thumbnail
if (result.hasThumbnail('image/jpeg')) {
const thumb = result.getThumbnailBuffer();
fs.writeFileSync('thumb.jpg', thumb);
}
```
--------------------------------
### Run Unit Tests
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Run the project's unit tests using the `nodeunit` test runner. Ensure `nodeunit` is installed globally.
```bash
nodeunit test/test-*.js
```
--------------------------------
### Create and Parse EXIF Data
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/types.md
Demonstrates the basic usage of the exif-parser library. First, create a parser instance with the image buffer, then call parse to get the EXIF results.
```javascript
const exifParser = require('exif-parser');
const parser = exifParser.create(buffer);
const result = parser.parse();
```
--------------------------------
### Full Exif Parsing Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Demonstrates a complete workflow: reading an image file, parsing its EXIF data, accessing tags, image dimensions, and extracting a JPEG thumbnail.
```javascript
const exifParser = require('exif-parser');
const fs = require('fs');
const buffer = fs.readFileSync('photo.jpg');
const parser = exifParser.create(buffer);
const result = parser.parse();
// Access tags
console.log(result.tags.Make); // Camera manufacturer
console.log(result.tags.Model); // Camera model
console.log(result.tags.DateTime); // Photo date/time
// Access image info
const size = result.getImageSize();
console.log(`Image: ${size.width}x${size.height}`);
// Extract thumbnail
if (result.hasThumbnail('image/jpeg')) {
const thumb = result.getThumbnailBuffer();
fs.writeFileSync('thumbnail.jpg', thumb);
}
```
--------------------------------
### Create EXIF Parser Instance
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/create.md
Use this snippet to create a parser instance from image data. Ensure you have the 'exif-parser' module installed and the image data available as a Buffer or ArrayBuffer. The parsing process can throw an error, so it's recommended to wrap the parse call in a try-catch block.
```javascript
const parser = require('exif-parser').create(imageBuffer);
try {
const result = parser.parse();
console.log(result.tags);
} catch(err) {
console.error('Failed to parse EXIF:', err);
}
```
--------------------------------
### BufferStream: Get Offset from Mark
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Calculates the byte offset from the last marked position to the current position.
```javascript
const offset = stream.offsetFrom();
```
--------------------------------
### Get All Tags with Names
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Retrieve all EXIF tags from an image buffer and display their resolved names. This is a common pattern for general metadata inspection.
```javascript
const parser = exifParser.create(buffer);
const result = parser.parse();
console.log(result.tags);
```
--------------------------------
### Get Raw Values (No Simplification)
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Configures the parser to return raw values without attempting to cast them to JavaScript types. This is useful for understanding the underlying EXIF data structure.
```javascript
const parser = exifParser.create(buffer)
.enableSimpleValues(false);
```
--------------------------------
### Internal EXIF Tag Processing Example
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif.md
Illustrates how the `parseTags` iterator callback is used within the `Parser` class to process EXIF tags. It shows conditional value simplification and tag name resolution.
```javascript
// In lib/parser.js
exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {
// Parse tags from all IFD sections
if (flags.simplifyValues) {
value = simplify.simplifyValue(value, format);
}
if (flags.resolveTagNames) {
// Map tag number to name and store in result.tags
}
});
```
--------------------------------
### Get Main Image Dimensions
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Retrieve the width and height of the main image. Returns an object with width and height properties, or undefined if the size could not be parsed.
```javascript
const size = result.getImageSize();
if (size) {
console.log(`Image is ${size.width}x${size.height}`);
}
```
--------------------------------
### Branch Stream
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/buffer-stream.md
Creates a new BufferStream that starts at a specified offset relative to the current position. The new stream has independent position tracking but reads from the same underlying buffer.
```javascript
branch(offset: number, length?: number): BufferStream
```
--------------------------------
### Get All Tags with Type Codes
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Retrieve all EXIF tags from an image buffer using their type codes instead of names. This is useful when tag names are not needed or when working with raw data.
```javascript
const parser = exifParser.create(buffer);
parser.enableTagNames(false);
const result = parser.parse();
console.log(result.tags[0]);
```
--------------------------------
### Handle Invalid EXIF Header
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/errors.md
Use a try-catch block to handle potential errors during EXIF parsing. This example specifically checks for the 'Invalid EXIF header' message, which occurs when the APP1 section lacks the correct header bytes. Recovery involves skipping the invalid section.
```javascript
const parser = require('exif-parser').create(corruptedBuffer);
try {
const result = parser.parse();
// If no valid EXIF headers were found, result.tags may be empty
if (!result.tags || Object.keys(result.result.tags).length === 0) {
console.log('No valid EXIF data found');
}
} catch (err) {
// This is unlikely unless the JPEG structure itself is invalid
console.error('Parse error:', err.message);
}
```
--------------------------------
### Get JPEG Image Size from SOF Section
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Extracts the image dimensions (width and height) from a JPEG Start of Frame (SOF) section. Requires a stream positioned at the SOF section.
```javascript
const { width, height } = getSizeFromSOFSection(stream);
```
--------------------------------
### getThumbnailLength()
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Gets the size in bytes of the thumbnail data.
```APIDOC
## getThumbnailLength()
### Description
Gets the size in bytes of the thumbnail data.
### Method Signature
```javascript
getThumbnailLength(): number
```
### Returns
- **number** - The byte length of the thumbnail.
### Example
```javascript
const length = result.getThumbnailLength();
console.log(`Thumbnail is ${length} bytes`);
```
```
--------------------------------
### getThumbnailOffset()
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Gets the absolute byte offset of the thumbnail data within the original buffer.
```APIDOC
## getThumbnailOffset()
### Description
Gets the absolute byte offset of the thumbnail data within the original buffer.
### Method Signature
```javascript
getThumbnailOffset(): number
```
### Returns
- **number** - The byte offset from the beginning of the original buffer.
### Example
```javascript
const offset = result.getThumbnailOffset();
const thumbBuffer = buffer.slice(offset, offset + result.getThumbnailLength());
```
```
--------------------------------
### Fluent Configuration with Method Chaining
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Demonstrates how to chain configuration methods for creating and parsing with exif-parser. All configuration methods return 'this' to enable chaining.
```javascript
const parser = require('exif-parser').create(buffer);
const result = parser
.enableImageSize(true)
.enableReturnTags(true)
.enableSimpleValues(true)
.parse();
```
--------------------------------
### BufferStream: Get Remaining Length
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Returns the number of bytes remaining in the stream from the current position.
```javascript
const remaining = stream.remainingLength();
```
--------------------------------
### Get Remaining Length
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/dom-buffer-stream.md
Returns the number of bytes remaining from the current position to the end of the stream.
```javascript
remainingLength(): number
```
--------------------------------
### Constructor Parameters
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Illustrates the parameters for the exif-parser create function. The primary parameter is the image data buffer.
```javascript
exif-parser.create(buffer, global)
```
--------------------------------
### Get Thumbnail Size
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Retrieve the dimensions of the embedded thumbnail. Returns an object with `width` and `height` properties.
```javascript
result.getThumbnailSize()
```
--------------------------------
### Create a Parser Instance
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/parser.md
Use exif-parser.create() to instantiate the Parser. This is the recommended way to create a parser object.
```javascript
const parser = require('exif-parser').create(buffer);
```
--------------------------------
### Get Image Dimensions
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/REFERENCE-OVERVIEW.md
Retrieves the width and height of the image from the parsed EXIF data. Returns null if dimensions are not available.
```javascript
const result = parser.parse();
const size = result.getImageSize();
if (size) {
console.log(`${size.width}x${size.height}`);
}
```
--------------------------------
### Get Thumbnail Buffer
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Retrieve the raw buffer (Node.js Buffer or browser ArrayBuffer) containing the embedded thumbnail image.
```javascript
result.getThumbnailBuffer()
```
--------------------------------
### Get Image Size
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Retrieve the image dimensions if `enableImageSize` was set to true. Returns an object with `width` and `height` properties.
```javascript
result.getImageSize()
```
--------------------------------
### Get Thumbnail Dimensions
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Retrieves the width and height of the embedded thumbnail. Returns undefined if no thumbnail exists or dimensions could not be determined.
```javascript
const thumbnailSize = result.getThumbnailSize();
if (thumbnailSize) {
console.log(`Thumbnail size: ${thumbnailSize.width}x${thumbnailSize.height}`);
}
```
--------------------------------
### Exif-Parser Public Entry Point
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/module-graph.md
The main entry point for the exif-parser library, responsible for creating and returning a Parser instance.
```APIDOC
## create
### Description
Creates a Parser instance, automatically detecting and wrapping the provided buffer (Node.js Buffer or browser ArrayBuffer) with the appropriate stream wrapper.
### Method
create
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **buffer** (Buffer | ArrayBuffer) - Required - The buffer containing EXIF data.
- **global** (object) - Optional - Global object, typically `window` in browsers.
### Returns
- Parser instance
```
--------------------------------
### Get Image Dimensions
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Retrieves the width and height of the main image. Returns undefined if image size was not enabled or could not be determined.
```javascript
const imageSize = result.getImageSize();
if (imageSize) {
console.log(`Image size: ${imageSize.width}x${imageSize.height}`);
}
```
--------------------------------
### Sequential Configuration
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Shows the equivalent of method chaining but using sequential method calls. This can be more readable for complex configurations or when setting options individually.
```javascript
const exifParser = require('exif-parser');
const parser = exifParser.create(buffer);
parser.enableImageSize(true);
parser.enableSimpleValues(true);
parser.enableTagNames(true);
const result = parser.parse();
```
--------------------------------
### Method Chaining Configuration
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Demonstrates how to configure the exif-parser using method chaining for a more concise API. Use this when you need to set multiple options at once.
```javascript
const exifParser = require('exif-parser');
const result = exifParser
.create(buffer)
.enableImageSize(true)
.enableSimpleValues(true)
.enableTagNames(true)
.parse();
```
--------------------------------
### Build Browser Bundle
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Build a browser-compatible bundle of the exif-parser library. This allows you to include it in HTML documents using a script tag.
```bash
git clone git@github.com:bwindels/exif-parser.git
cd exif-parser/
make build-browser-bundle
```
--------------------------------
### Full Details Configuration: Include Pointers and Binary Fields
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Enable this configuration to include pointer/offset tags and binary format fields in the results. This provides the most comprehensive data extraction.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enablePointers(true);
parser.enableBinaryFields(true);
const result = parser.parse();
// result.tags now includes ThumbnailOffset, ThumbnailLength
// result.tags now includes binary (Buffer/ArrayBuffer) field values
```
--------------------------------
### Create ExifParser Instance in Browser
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/REFERENCE-OVERVIEW.md
Instantiate the ExifParser globally in a browser environment after building the bundle. The parser is available under the `ExifParser` namespace.
```javascript
window.ExifParser.create(arrayBuffer)
```
--------------------------------
### Get Thumbnail Byte Length
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Retrieves the size in bytes of the thumbnail data. Use this value to determine how many bytes to read for the thumbnail.
```javascript
const length = result.getThumbnailLength();
console.log(`Thumbnail is ${length} bytes`);
```
--------------------------------
### Minimal Configuration: Extract Only Tags
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Use this configuration when you only need EXIF tag data and do not require image dimensions. Ensure `enableReturnTags` is set to true.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enableImageSize(false);
parser.enableReturnTags(true);
const result = parser.parse();
console.log(result.tags); // Only tags, no size info
```
--------------------------------
### Get Thumbnail Dimensions
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Retrieve the width and height of the embedded thumbnail image. This method parses the SOF section of the thumbnail and only works for JPEG thumbnails.
```javascript
const thumbSize = result.getThumbnailSize();
if (thumbSize) {
console.log(`Thumbnail is ${thumbSize.width}x${thumbSize.height}`);
}
```
--------------------------------
### BufferStream: Branch Read
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Performs a read operation starting from the marked position without advancing the main stream pointer. Useful for nested structures.
```javascript
const branchedValue = stream.branch(callback);
```
--------------------------------
### Create Parser Instance (Node.js/Browser)
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Create a new exif-parser instance. The parser can accept a Node.js Buffer or a DOM ArrayBuffer. The `parse` method may throw an error for invalid data.
```javascript
var parser = require('exif-parser').create(buffer);
try {
var result = parser.parse();
} catch(err) {
// got invalid data, handle error
}
```
--------------------------------
### Get Thumbnail Offset and Length
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Retrieves the byte offset and length of the thumbnail data within the original image buffer. Useful for manual extraction or verification.
```javascript
const thumbnailOffset = result.getThumbnailOffset();
const thumbnailLength = result.getThumbnailLength();
```
--------------------------------
### Instantiate Parser with Node.js Buffer
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Creates a new Parser instance using a Node.js Buffer. The environment is auto-detected, and no initial configuration is needed.
```javascript
const fs = require('fs');
const exifParser = require('exif-parser');
const buffer = fs.readFileSync('/path/to/image.jpg');
const parser = exifParser.create(buffer);
```
--------------------------------
### Parsing EXIF Data with Error Handling
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/START-HERE.md
Shows how to create an exifParser instance, parse EXIF data from a buffer, and catch potential errors during the parsing process. Common error messages are provided for debugging.
```javascript
const parser = exifParser.create(buffer);
try {
const result = parser.parse();
} catch (err) {
// Common errors:
// "Invalid JPEG section offset" — JPEG is corrupted/truncated
// "Invalid EXIF header" — EXIF metadata is corrupted (usually silently skipped)
console.error('Parse failed:', err.message);
}
```
--------------------------------
### Create Branch Stream
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/dom-buffer-stream.md
Creates a new, independent DOMBufferStream that starts at a specified relative offset within the current stream. An optional length can also be provided.
```javascript
branch(offset: number, length?: number): DOMBufferStream
```
--------------------------------
### Main Module Export
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/types.md
Exports the main 'create' function for the Exif-Parser, which takes a buffer or ArrayBuffer and an optional global object to return a Parser instance.
```javascript
module.exports = {
create: (buffer: Buffer | ArrayBuffer, global?: object) => Parser
}
```
--------------------------------
### Get Raw GPS Coordinates as Arrays
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Disables simplified values to retrieve raw GPS coordinates as arrays of degrees, minutes, and seconds. Use 'enableSimpleValues(false)' for this.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enableSimpleValues(false); // Raw values
const result = parser.parse();
if (result.tags.GPSLatitude) {
const [degrees, minutes, seconds] = result.tags.GPSLatitude;
console.log(`${degrees}° ${minutes}' ${seconds}"`);
// Output: 40° 26' 46.2"
}
```
--------------------------------
### Get Thumbnail Byte Offset
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Retrieves the absolute byte offset of the thumbnail data within the original buffer. This can be used in conjunction with getThumbnailLength to extract the thumbnail buffer.
```javascript
const offset = result.getThumbnailOffset();
const thumbBuffer = buffer.slice(offset, offset + result.getThumbnailLength());
```
--------------------------------
### Minimal Configuration: Extract Only Image Size
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Use this configuration when you only need the image dimensions and not the EXIF tag data. Set `enableReturnTags` to false.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enableReturnTags(false);
const result = parser.parse();
const size = result.getImageSize(); // Only size, no tags
```
--------------------------------
### Instantiate Parser with Browser ArrayBuffer
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Creates a new Parser instance using a browser's ArrayBuffer. The environment is auto-detected, and no initial configuration is needed.
```javascript
const exifParser = require('exif-parser');
// Assuming 'arrayBuffer' is obtained from a file input or fetch
const parser = exifParser.create(arrayBuffer);
```
--------------------------------
### Browser Usage of Exif-Parser
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/REFERENCE-OVERVIEW.md
Include the library script and initialize the parser with an ArrayBuffer in modern browsers. For older browsers, consider using a polyfill or server-side pre-processing.
```html
```
--------------------------------
### Parse All EXIF Tags from APP1
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Parses all EXIF tags contained within the APP1 section of an image stream. Requires a stream positioned at the start of the APP1 data.
```javascript
const tags = parseTags(stream, iterator);
```
--------------------------------
### Exif-Parser Configuration
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/MANIFEST.md
Details on the configuration methods available for the Parser class.
```APIDOC
## Configuration
### Description
Methods to configure the behavior of the Exif-Parser.
### Methods
- `enableBinaryFields()`
- `enablePointers()`
- `enableTagNames()`
- `enableImageSize()`
- `enableReturnTags()`
- `enableSimpleValues()
```
--------------------------------
### Enable Simple Date Values in Parser
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/date.md
Demonstrates how to enable simple date value parsing within the exif-parser. When enabled, date tags are converted to Unix timestamps.
```javascript
const parser = require('exif-parser').create(buffer);
const result = parser.parse();
// Tags with dates are now Unix timestamps instead of strings
if (result.tags.DateTimeOriginal) {
const date = new Date(result.tags.DateTimeOriginal * 1000);
console.log(date);
}
```
--------------------------------
### getSizeFromSOFSection
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/jpeg.md
Extracts image dimensions (width and height) from the SOF (Start of Frame) marker data. The stream should be positioned after the 2-byte SOF section size and be in big-endian mode.
```APIDOC
## getSizeFromSOFSection(stream)
### Description
Extract image dimensions from SOF (Start of Frame) marker data.
### Method
```javascript
getSizeFromSOFSection(stream: BufferStream | DOMBufferStream): {width: number, height: number}
```
### Parameters
#### Path Parameters
- **stream** (BufferStream | DOMBufferStream) - Required - Stream positioned after the 2-byte SOF section size (at the precision byte). Must be in big-endian mode.
### Returns
Object with `width` and `height` properties in pixels.
### Remarks
- Skips 1 byte (precision) after the section size
- Reads height as UInt16 (2 bytes)
- Reads width as UInt16 (2 bytes)
### Example
```javascript
jpeg.parseSections(stream, (markerType, sectionStream) => {
const name = jpeg.getSectionName(markerType);
if (name.name === 'SOF') {
const size = jpeg.getSizeFromSOFSection(sectionStream);
console.log(`Image size: ${size.width}x${size.height}`);
}
});
```
```
--------------------------------
### Environment Detection for Parser Creation
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Illustrates how exif-parser automatically detects the environment (Node.js or browser) and accepts the appropriate data type (Buffer or ArrayBuffer) for creating a parser instance.
```javascript
const exifParser = require('exif-parser');
// Node.js - pass a Buffer
const nodeBuffer = fs.readFileSync('photo.jpg');
const parser1 = exifParser.create(nodeBuffer);
// Browser - pass an ArrayBuffer
const arrayBuffer = await file.arrayBuffer();
const parser2 = exifParser.create(arrayBuffer);
```
--------------------------------
### Parser Methods
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Demonstrates the usage of parser methods, highlighting type consistency for boolean flags and the absence of varargs or optional middle parameters. It also shows the consistent return types for method chaining and result retrieval.
```APIDOC
## Parser Methods
### Description
This section details the methods available for interacting with the Exif-Parser. It emphasizes the consistent use of data types for parameters and return values, promoting predictable behavior and ease of use.
### Methods
- `enableImageSize(boolean)`: Enables the retrieval of image dimensions. Accepts a boolean value. Returns the Parser instance for chaining.
- `enableTagNames(boolean)`: Enables the retrieval of tag names. Accepts a boolean value. Returns the Parser instance for chaining.
- `parse()`: Parses the EXIF data. Accepts no parameters. Returns an ExifResult object.
### Type Consistency
All methods maintain consistent parameter types. Boolean parameters are used for enabling or disabling features, and there are no varargs or optional middle parameters. The return types are also consistent: methods like `enableImageSize` and `enableTagNames` return the Parser instance for chaining, while `parse` returns an ExifResult object.
```
--------------------------------
### Typical JPEG Parsing Usage
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/jpeg.md
Demonstrates typical usage patterns for the jpeg module within a larger parsing context. This includes extracting image size and EXIF data from specific JPEG sections.
```javascript
// In parser.js - extract image size
jpeg.parseSections(stream, function(sectionType, sectionStream) {
if (flags.imageSize && jpeg.getSectionName(sectionType).name === 'SOF') {
imageSize = jpeg.getSizeFromSOFSection(sectionStream);
}
});
// Extract EXIF from APP1 section
if (sectionType === 0xE1) { // APP1
exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {
// Process tag
});
}
```
--------------------------------
### exif-parser.create()
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/create.md
Creates an EXIF parser instance from a buffer containing JPEG image data. It supports both Node.js Buffers and DOM ArrayBuffers.
```APIDOC
## create(buffer, global)
### Description
Creates an EXIF parser instance from a buffer containing JPEG image data. The function automatically detects the buffer type and sets up the appropriate stream wrapper.
### Method
create
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
- **buffer** (Buffer | ArrayBuffer) - Required - Node Buffer or DOM ArrayBuffer containing JPEG image data. The first 65635 bytes are sufficient.
- **global** (object) - Optional - The global object context, used internally for environment detection. Defaults to detected environment.
### Return Type
`Parser` — An instance of the Parser class configured with an appropriate buffer streaming backend.
### Errors
Throws `Error` with message "Invalid EXIF header" if the EXIF data contains invalid header bytes during parsing.
### Example Usage
```javascript
const parser = require('exif-parser').create(imageBuffer);
try {
const result = parser.parse();
console.log(result.tags);
} catch(err) {
console.error('Failed to parse EXIF:', err);
}
```
```
--------------------------------
### Raw Values Configuration: Disable Simplification
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Disable value simplification to get raw EXIF data formats for numbers, dates, and fractions. This is useful for precise data handling or debugging.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enableSimpleValues(false);
const result = parser.parse();
// GPS: result.tags.GPSLatitude = [40, 26, 46.2] (array, not decimal)
// Dates: result.tags.DateTimeOriginal = "2023:12:25 14:30:45" (string, not timestamp)
// Fractions: result.tags.XResolution = [300, 1] (array, not 300)
```
--------------------------------
### Enable Pointers
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/parser.md
Include pointer tags in the results. Pointer tags indicate offsets to other EXIF sections.
```javascript
parser.enablePointers(true).parse();
```
--------------------------------
### Performance: Skip Tags, Get Size Only
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/REFERENCE-OVERVIEW.md
Parses an image buffer efficiently by disabling tag return, allowing for faster retrieval of image dimensions. This is useful when only size information is needed.
```javascript
const result = parser
.enableReturnTags(false)
.parse();
const size = result.getImageSize();
```
--------------------------------
### Basic Error Handling with Try-Catch
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/errors.md
Use a try-catch block to gracefully handle potential errors during file reading and EXIF parsing. This snippet demonstrates catching common issues like truncated or corrupt files.
```javascript
const exifParser = require('exif-parser');
const fs = require('fs');
try {
const buffer = fs.readFileSync('photo.jpg');
const parser = exifParser.create(buffer);
const result = parser.parse();
console.log(result.tags);
} catch (err) {
console.error('Failed to parse EXIF:', err.message);
// Log for debugging:
// - "Invalid JPEG section offset" → File is truncated
// - "Invalid EXIF header" → File has corrupt EXIF
// - "Invalid TIFF header" → TIFF structure is malformed
// - "Invalid TIFF data" → TIFF magic number missing
}
```
--------------------------------
### Exif-Parser Public API
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/MANIFEST.md
This section details the public API of the Exif-Parser library, including the factory function `create` and the `Parser` class with its methods and the `ExifResult` class.
```APIDOC
## Public API
### `exif-parser.create()`
#### Description
Factory function to create a new Exif-Parser instance.
### `Parser` Class
#### Description
Represents the Exif parser. It has several configuration methods.
#### Methods
- `enableBinaryFields()`: Enables binary fields.
- `enablePointers()`: Enables pointers.
- `enableTagNames()`: Enables tag names.
- `enableImageSize()`: Enables image size retrieval.
- `enableReturnTags()`: Enables returning tags.
- `enableSimpleValues()`: Enables simple value formatting.
### `Parser.parse()`
#### Description
Main method to parse EXIF data from a buffer.
### `ExifResult` Class
#### Description
Represents the result of EXIF parsing. It provides accessor methods for EXIF data.
#### Methods
- Accessor methods for EXIF data (6 methods).
```
--------------------------------
### Exif-Parser Architecture Overview
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
This snippet outlines the main components of the exif-parser, including the Parser class with its methods for JPEG and EXIF parsing, and stream classes for Node.js and browser environments. It also details the configuration flags and the structure of the result object.
```tree
index.js
├─ Parser (lib/parser.js)
│ ├─ jpeg.parseSections() → JPEG navigation
│ ├─ exif.parseTags() → EXIF tag extraction
│ └─ simplify → Value type conversion
├─ BufferStream (lib/bufferstream.js) [Node.js]
└─ DOMBufferStream (lib/dom-bufferstream.js) [Browser]
Parser Configuration (6 enable/disable flags):
├─ enableBinaryFields → Include format 7 (binary) fields
├─ enablePointers → Include offset/pointer tags
├─ enableTagNames → Resolve tag codes to names
├─ enableImageSize → Extract image dimensions
├─ enableReturnTags → Include tags in result
└─ enableSimpleValues → Cast values to JS types
Result (ExifResult):
├─ tags → {tagName: value} or [{section, type, value}]
├─ imageSize → {width, height}
└─ Thumbnail methods
├─ hasThumbnail(mime?)
├─ getThumbnailSize()
├─ getThumbnailBuffer()
└─ getThumbnailOffset()
```
--------------------------------
### Tag Codes Configuration: Disable Tag Names
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Disable the resolution of tag codes to human-readable names to get tag codes instead. The result.tags will be an array of objects with section, type, and value.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enableTagNames(false);
const result = parser.parse();
// result.tags is an array:
// [{section: 1, type: 271, value: 'Canon'}, {section: 1, type: 272, value: '5D'}, ...]
```
--------------------------------
### Default Configuration Object
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Shows the default configuration object used by exif-parser when a Parser is created. This object outlines the initial settings for various parsing options.
```javascript
{
readBinaryTags: false, // enableBinaryFields(false)
resolveTagNames: true, // enableTagNames(true)
simplifyValues: true, // enableSimpleValues(true)
imageSize: true, // enableImageSize(true)
hidePointers: true, // enablePointers(false)
returnTags: true // enableReturnTags(true)
}
```
--------------------------------
### Public Entry Point Export
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/module-graph.md
The main export from index.js, which is a function to create a Parser instance. It handles buffer type detection and stream creation.
```javascript
module.exports = {
create: function(buffer, global)
}
```
--------------------------------
### Convert GPS Degrees to Decimal
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/simplify.md
Converts GPS latitude and longitude values from degree/minute/second arrays and reference characters ('N'/'S', 'E'/'W') into decimal degrees. Requires callbacks to get and set tag values.
```javascript
castDegreeValues(
t => tags[t.name],
(t, v) => { tags[t.name] = v; }
);
```
--------------------------------
### Debugging: Include All Data
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/configuration.md
Enables all available data parsing options for debugging purposes, including pointers, binary fields, and raw tag formats. This is useful for inspecting all available EXIF data.
```javascript
const parser = require('exif-parser').create(buffer);
parser.enablePointers(true);
parser.enableBinaryFields(true);
parser.enableTagNames(false);
parser.enableSimpleValues(false);
const result = parser.parse();
// result.tags is an array with all tags in raw format
console.log(result.tags);
```
--------------------------------
### Convert EXIF Dates to Unix Timestamps
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/simplify.md
Parses EXIF date fields (ModifyDate, DateTimeOriginal, CreateDate) into Unix timestamps. Recognizes standard EXIF and ISO 8601 formats. Requires callbacks to get and set tag values.
```javascript
castDateValues(
t => tags[t.name],
(t, v) => { tags[t.name] = v; }
);
```
--------------------------------
### BufferStream Constructor
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/buffer-stream.md
BufferStream is not typically instantiated directly. It's created internally by exif-parser.create(). Parameters include the buffer, an optional offset, length, and endianness setting.
```javascript
new BufferStream(buffer: Buffer, offset?: number, length?: number, bigEndian?: boolean)
```
--------------------------------
### Typical EXIF Parse Call Sequence
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/module-graph.md
Illustrates the sequence of calls involved in parsing EXIF data from a JPEG file, including section detection, tag parsing, and post-processing steps.
```text
exif-parser.create()
↓
index.js: detect Buffer type
↓
new Parser(stream)
↓
parser.parse()
↓
jpeg.parseSections(stream, iterator)
├─ For each JPEG section
├─ If section type = 0xE1 (APP1, EXIF):
│ ├─ exif.parseTags(stream, iterator)
│ │ ├─ readHeader() → Validate TIFF structure
│ │ ├─ readIFDSection(IFD0) → Parse main tags
│ │ ├─ readIFDSection(IFD1) → Parse thumbnail tags (if offset present)
│ │ ├─ readIFDSection(GPSIFD) → Parse GPS tags (if offset present)
│ │ └─ readIFDSection(SubIFD/InteropIFD) → Parse sub/interop tags
│ │
│ └─ For each tag:
│ └─ iterator() callback invoked
│ ├─ Check hidePointers flag
│ ├─ Check readBinaryTags flag
│ ├─ If simplifyValues:
│ │ └─ simplify.simplifyValue()
│ ├─ If resolveTagNames:
│ │ └─ exif-tags.exif[tagType] → Get tag name
│ └─ Store in result.tags
│
└─ If section type = SOF (0xC0-0xCF):
└─ jpeg.getSizeFromSOFSection() → Extract image dimensions
Post-processing (if simplifyValues):
├─ simplify.castDegreeValues() → GPS arrays to decimal degrees
└─ simplify.castDateValues() → Date strings to timestamps
└─ date.parseExifDate()
Return ExifResult
```
--------------------------------
### Enable Binary Fields and Pointers
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/INDEX.md
Configures the parser to include binary data fields and offset/pointer tags in the results. This is useful for detailed analysis.
```javascript
const parser = exifParser.create(buffer)
.enableBinaryFields(true)
.enablePointers(true);
```
--------------------------------
### Accessing ExifResult Methods
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/START-HERE.md
Demonstrates how to access various data points and metadata from the parsed EXIF result object, such as tags, image dimensions, and thumbnail information.
```javascript
result.tags // EXIF tags
result.getImageSize() // {width, height}
result.hasThumbnail(mime) // boolean
result.getThumbnailBuffer() // Buffer or ArrayBuffer
result.getThumbnailSize() // {width, height}
```
--------------------------------
### Set Configuration Defaults
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/README.md
Configure the parser's behavior by enabling or disabling specific features like binary fields, pointers, tag names, image size extraction, return tags, and simple value casting.
```javascript
parser.enableBinaryFields(false);
parser.enablePointers(false);
parser.enableTagNames(true);
parser.enableImageSize(true);
parser.enableReturnTags(true);
parser.enableSimpleValues(true);
```
--------------------------------
### Default Parser Configuration
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/types.md
Provides the default values for the parser configuration flags. These settings are applied unless explicitly overridden.
```javascript
{
readBinaryTags: false,
resolveTagNames: true,
simplifyValues: true,
imageSize: true,
hidePointers: true,
returnTags: true
}
```
--------------------------------
### enablePointers
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/parser.md
Configures the parser to include pointer tags in the results. Pointer tags indicate offsets to other EXIF sections and do not contain image information.
```APIDOC
## enablePointers(enable: boolean): Parser
### Description
Include pointer tags in the result. Pointer tags indicate offsets to other EXIF sections and do not contain image information.
### Parameters
#### Query Parameters
- **enable** (boolean) - Required - If true, pointer tags (0x0201, 0x0202, 0x0103) are included in results.
### Returns
`Parser` (this)
### Example
```javascript
parser.enablePointers(true).parse();
```
```
--------------------------------
### enableReturnTags
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/parser.md
Configures whether EXIF tags should be included in the parsing results. Useful when only image size information is required.
```APIDOC
## enableReturnTags(enable: boolean): Parser
### Description
Include EXIF tags in the result.
### Parameters
#### Query Parameters
- **enable** (boolean) - Required - If false, result.tags will be empty; useful when only image size is needed.
### Returns
`Parser` (this)
### Example
```javascript
const result = parser.enableReturnTags(false).parse();
const size = result.getImageSize(); // Only size, no tags
```
```
--------------------------------
### ImageSize Interface
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/types.md
Dimensions of an image (main or thumbnail).
```APIDOC
## ImageSize Interface
### Description
Dimensions of an image (main or thumbnail).
### Properties
- `width` (number) - The width of the image.
- `height` (number) - The height of the image.
```
--------------------------------
### getImageSize()
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/exif-result.md
Retrieves the width and height of the main image.
```APIDOC
## getImageSize()
### Description
Retrieves the width and height of the main image.
### Method Signature
```javascript
getImageSize(): {width: number, height: number} | undefined
```
### Returns
- **object** - An object with `width` and `height` properties in pixels, or `undefined` if image size was not parsed.
### Example
```javascript
const size = result.getImageSize();
if (size) {
console.log(`Image is ${size.width}x${size.height}`);
}
```
```
--------------------------------
### Marker Interface
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/types.md
Internal object for position tracking within a buffer.
```APIDOC
## Marker Interface
### Description
Internal object for position tracking within a buffer.
### Properties
- `offset` (number) - The current offset within the buffer.
### Methods
- `openWithOffset(offset: number): BufferStream | DOMBufferStream` - Opens a stream at a specified offset.
- `getParentOffset?(): number` - Returns the offset of the parent marker, if available.
```
--------------------------------
### Enable Simple Values
Source: https://github.com/bwindels/exif-parser/blob/master/README.md
Enable the casting of EXIF values to appropriate JavaScript types like numbers and Dates. This simplifies working with various EXIF value formats.
```javascript
parser.enableSimpleValues([boolean]);
```
--------------------------------
### DOMBufferStream Constructor
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/api-reference/dom-buffer-stream.md
Initializes a new DOMBufferStream instance to read from an ArrayBuffer. While not typically instantiated directly by users, understanding its parameters is useful for comprehending its internal workings.
```APIDOC
## DOMBufferStream Constructor
### Description
Initializes a new DOMBufferStream instance to read from an ArrayBuffer. This constructor is typically called internally by `exif-parser.create()` when an ArrayBuffer is provided.
### Parameters
#### Path Parameters
- **arrayBuffer** (ArrayBuffer) - Required - The ArrayBuffer to read from.
- **offset** (number) - Optional - Starting byte position. Defaults to 0.
- **length** (number) - Optional - Number of bytes available. Defaults to `byteLength - offset`.
- **bigEndian** (boolean) - Optional - If true, use big-endian byte order. If false, use little-endian. Defaults to `undefined`.
- **global** (object) - Optional - Global object context (window or globalThis). Defaults to `undefined`.
- **parentOffset** (number) - Optional - Internal tracking for nested buffer offsets. Defaults to 0.
```
--------------------------------
### Accessing Tags When Enabled
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/REFERENCE-OVERVIEW.md
Shows how to access EXIF tags as properties of the 'tags' object when 'enableTagNames' is true (default).
```javascript
result.tags.Make;
result.tags.Model;
```
--------------------------------
### Date Parsing Functions
Source: https://github.com/bwindels/exif-parser/blob/master/_autodocs/module-graph.md
Exports functions for parsing various EXIF date and time formats.
```APIDOC
## Date Module Exports
### Description
Provides functions for parsing and converting EXIF date and time strings into JavaScript Date objects or timestamps.
### Exports
- `parseExifDate(dateTimeStr)`: Parses a standard EXIF date-time string.
- `parseDateWithSpecFormat(dateTimeStr)`: Parses a date-time string with a specific format.
- `parseDateWithTimezoneFormat(dateTimeStr)`: Parses a date-time string including timezone information.
```