istextorbinary

repository·master·Indexed 41 days ago

https://github.com/bevry/istextorbinary

A high-accuracy utility for determining if a filename or buffer is text or binary. Version 9.5.0 features a two-step detection process combining extension checks with multi-point buffer inspection (start, middle, and end). It provides APIs including isText(), isBinary(), and getEncoding() to identify UTF-8 or binary data, with support for Node.js, Deno, and browser environments.

Tokens
2.1K
Snippets
8
Records
12
Agent score
99%

What's inside istextorbinary

  1. How isTextOrBinary determines if a file is text or binary

    master

    The library uses a two-step detection process to ensure high accuracy and performance:

    1. Extension Check: If a filename is provided, the library checks its extensions from right to left against known text and binary extension lists. This allows for accurate detection of files with multiple extensions (e.g., app.x.y).
    2. Contents Check: If no filename is provided, or if the extension check is indeterminate, the library inspects the buffer contents. It checks 24 bytes at the start, middle, and end of the buffer. This three-location check is designed to be more accurate than single-location checks while remaining more performant than scanning large chunks of data.

    Note: The combination of extension and content checks is necessary because UTF-16 characters can be indistinguishable from binary data if only content is checked.

  2. Install istextorbinary via CDN (Skypack, unpkg, jspm)

    master

    For browser-based usage using ES Modules, you can use one of the following CDNs:

    Skypack

    <script type="module">
        import * as pkg from '//cdn.skypack.dev/istextorbinary@^9.5.0'
    </script>

    unpkg

    <script type="module">
        import * as pkg from '//unpkg.com/istextorbinary@^9.5.0'
    </script>

    jspm

    <script type="module">
        import * as pkg from '//dev.jspm.io/istextorbinary@9.5.0'
    </script>
  3. Use isText, isBinary, and getEncoding APIs

    master

    The library provides three primary functions to detect file types and encodings:

    • isText(aFilename, aBuffer): Returns true if the file is text, false if binary, or null if both arguments are null.
    • isBinary(aFilename, aBuffer): Returns true if the file is binary, false if text, or null if both arguments are null.
    • getEncoding(aBuffer): Returns 'utf8' if the buffer contains only UTF-8 characters, otherwise returns 'binary'.

    Arguments can be passed individually (e.g., passing null for the filename to check only the buffer).

    import { isText, isBinary, getEncoding } from 'istextorbinary'
    
    // Check filename only
    isText('example.txt') 
    
    // Check buffer only
    isText(null, aBuffer) 
    
    // Check both (filename then buffer)
    isText('example.txt', aBuffer) 
    
    // Check binary status
    isBinary('image.png', aBuffer)
    
    // Get encoding
    const encoding = getEncoding(aBuffer) // 'utf8' or 'binary'
  4. Configure getEncoding() options

    master

    You can fine-tune the getEncoding detection by passing an EncodingOpts object. This is useful if you want to target a specific offset or change the size of the inspected chunk.

    EncodingOpts properties:

    • chunkLength (number, default: 24): The number of bytes to inspect in a single chunk.
    • chunkBegin (number, optional): The starting byte offset for the inspection. If chunkBegin is not provided, the function defaults to its multi-pass (start, middle, end) strategy. If provided, it performs a single check at that specific location.
    import { getEncoding, type EncodingOpts } from 'istextorbinary';
    
    const opts: EncodingOpts = {
      chunkLength: 64,
      chunkBegin: 1024
    };
    
    const encoding = getEncoding(buffer, opts);
    // Note: Providing chunkBegin disables the automatic start/middle/end multi-pass check.
  5. Reference the istextorbinary Editions

    master

    The package is published with multiple editions to support various environments. You can target specific editions by adjusting the import path:

    • istextorbinary: Uses the Editions Autoloader to select the correct edition automatically.
    • istextorbinary/source/index.ts: TypeScript source code.
    • istextorbinary/edition-browsers/index.js: Compiled against ES2022 for browsers (ESM).
    • istextorbinary/edition-es2022/index.js: Compiled against ES2022 for Node.js 14+ (CJS).
    • istextorbinary/edition-es2017/index.js: Compiled against ES2017 for older Node.js versions (CJS).
    • istextorbinary/edition-es5/index.js: Compiled against ES5 for older Node.js versions (CJS).
    • istextorbinary/edition-es2017-esm/index.js: Compiled against ES2017 for Node.js 12+ (ESM).
    • istextorbinary/edition-types/index.d.ts: TypeScript definitions.
    • istextorbinary/edition-deno/index.ts: Deno-compatible TypeScript source.
  6. isText() - Detect if content is text

    master

    Determines if a file or buffer is text. The detection logic follows this priority:

    1. Extension Check: If a filename is provided, it checks the file extension against known text and binary extension lists. This is the fastest method.
    2. Encoding Check: If the extension is unknown or no filename is provided, it falls back to inspecting the buffer using getEncoding().

    Returns true if text, false if binary, or null if neither filename nor buffer were provided.

    import { isText } from 'istextorbinary';
    
    // Using filename for fast extension check
    const isTextFile = isText('example.txt'); // true
    
    // Using buffer for encoding detection
    const isTextBuffer = isText(undefined, buffer);
    
    // No info provided
    const result = isText(); // null
  7. isBinary() - Detect if content is binary

    master

    Determines if a file or buffer is binary. It is a convenience wrapper around isText() that returns the inverse result.

    Returns true if binary, false if text, or null if neither filename nor buffer were provided.

    import { isBinary } from 'istextorbinary';
    
    const isBinaryFile = isBinary('image.png'); // true
    const isBinaryBuffer = isBinary(undefined, buffer); // true/false/null
  8. getEncoding() - Get buffer encoding

    master

    Inspects a buffer to determine if its encoding is 'utf8' or 'binary'.

    Detection Strategy: By default, the function performs a multi-pass check to ensure accuracy. It inspects the start, middle, and end of the buffer for characters that are invalid in UTF-8. This is necessary because a buffer might appear to be UTF-8 in one section but contain binary data in another.

    Returns:

    • 'utf8' if the buffer is valid text.
    • 'binary' if invalid UTF-8 characters (like control characters $\le 8$ or the replacement character �) are found.
    • null if no buffer is provided.
    import { getEncoding } from 'istextorbinary';
    
    const encoding = getEncoding(buffer); // 'utf8' | 'binary' | null
  9. Import isTextOrBinary in CommonJS

    master

    To use isTextOrBinary in a CommonJS environment, require the package directly. The package exports a function that determines if a given input (typically a Buffer or Uint8Array) represents text or binary data.

    const isTextOrBinary = require('istextorbinary');
    
    // Example usage (assuming input is a Buffer or Uint8Array)
    const result = isTextOrBinary(someBuffer);
    console.log(result); // true if text, false if binary
  10. EncodingOpts type definition

    master

    The EncodingOpts interface defines configuration for the getEncoding function.

    export interface EncodingOpts {
    	/** Defaults to 24 */
    	chunkLength?: number;
    
    	/** If not provided, will check the start, middle, and end */
    	chunkBegin?: number;
    }