### Install isBinaryFile Source: https://github.com/gjtorikian/isbinaryfile/blob/main/README.md Install the isbinaryfile package using npm. ```bash npm install isbinaryfile ``` -------------------------------- ### Async and Sync Usage Examples Source: https://github.com/gjtorikian/isbinaryfile/blob/main/README.md Demonstrates how to use both the asynchronous isBinaryFile and synchronous isBinaryFileSync functions with file paths and buffers. Includes an example of specifying the size option for partial buffer checks. ```javascript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; import fs from 'fs'; const filename = 'fixtures/pdf.pdf'; // Async with file path const result = await isBinaryFile(filename); if (result) { console.log('It is binary!'); } else { console.log('No it is not.'); } // Sync with buffer const bytes = fs.readFileSync(filename); console.log(isBinaryFileSync(bytes)); // true or false // With explicit size option const partialBuffer = Buffer.alloc(100); fs.readSync(fs.openSync(filename, 'r'), partialBuffer, 0, 100, 0); console.log(isBinaryFileSync(partialBuffer, { size: 100 })); ``` -------------------------------- ### IsBinaryOptions Usage Examples Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/types.md Demonstrates how to use the IsBinaryOptions interface with isBinaryFile and isBinaryFileSync functions, including specifying encoding hints and size limits. ```typescript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // With encoding hint for UTF-16 files await isBinaryFile('document.txt', { encoding: 'utf-16' }); // With size limit for Buffer analysis const buffer = Buffer.alloc(512); // ... read data into buffer ... isBinaryFileSync(buffer, { size: 256 }); // With both options isBinaryFileSync(buffer, { encoding: 'big5', size: bytesRead }); ``` -------------------------------- ### Good Practice: Use Specific Encoding Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This example shows the recommended way to use a specific encoding hint for a CJK file. ```typescript // ✓ GOOD - Specific encoding for CJK file isBinaryFileSync('file.txt', { encoding: 'big5' }); ``` -------------------------------- ### Basic Usage of isBinaryFile and isBinaryFileSync Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/README.md Demonstrates the basic usage of both the asynchronous and synchronous functions for checking if a file is binary. Includes examples with and without options. ```typescript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // Async const isBinary = await isBinaryFile('file.pdf'); // Sync const isBinary = isBinaryFileSync('file.txt'); // With options const isBinary = isBinaryFileSync('file.txt', { encoding: 'utf-16' }); ``` -------------------------------- ### Good Practice: Fall Back to Generic CJK Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This example demonstrates the recommended approach of using a generic 'cjk' hint when the exact encoding is uncertain. ```typescript // ✓ GOOD - Generic CJK when exact encoding unknown isBinaryFileSync('asian-file.txt', { encoding: 'cjk' }); ``` -------------------------------- ### EncodingHint Usage Examples Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/types.md Illustrates various ways to use EncodingHint values with isBinaryFile and isBinaryFileSync for different character sets and endianness. ```typescript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // UTF-16 with automatic endianness detection const utf16 = await isBinaryFile('file.txt', { encoding: 'utf-16' }); // Explicit endianness const utf16le = isBinaryFileSync('file.txt', { encoding: 'utf-16le' }); const utf16be = isBinaryFileSync('file.txt', { encoding: 'utf-16be' }); // Western European const latin = isBinaryFileSync('document.txt', { encoding: 'latin1' }); // CJK with specific encoding const chinese = isBinaryFileSync('text.txt', { encoding: 'big5' }); const korean = isBinaryFileSync('text.txt', { encoding: 'euc-kr' }); // Generic CJK when encoding is unknown const cjk = isBinaryFileSync('text.txt', { encoding: 'cjk' }); ``` -------------------------------- ### Testing Binary File Detection with Various Cases Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/DETECTION-ALGORITHM.md Provides example test cases for the isBinaryFileSync function, including null byte files, UTF-8 text, and UTF-16 encoded content. Asserts the expected binary status against the actual result. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { readFileSync } from 'fs'; // Create test cases const testCases = [ { name: 'null_byte.bin', content: Buffer.from([0x00, 0x01, 0x02]), expected: true }, { name: 'utf8_text.txt', content: Buffer.from('Hello World'), expected: false }, { name: 'utf16_le.txt', content: Buffer.from([0x48, 0x00, 0x69, 0x00]), expected: false }, ]; testCases.forEach(test => { const result = isBinaryFileSync(test.content); console.assert(result === test.expected, `${test.name}: expected ${test.expected}, got ${result}`); }); ``` -------------------------------- ### Check File Buffer Synchronously Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/README.md This example demonstrates how to check if a file is binary by passing its buffer content to the `isBinaryFileSync` function. This is useful when the file content is already loaded into memory. ```typescript const buffer = readFileSync('file'); const isBinary = isBinaryFileSync(buffer); ``` -------------------------------- ### With explicit size parameter for partial reads Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfile.md Use this example to check a Buffer for binary content when you have only read a portion of the file. The 'size' option specifies the number of bytes to scan. ```typescript import { isBinaryFile } from 'isbinaryfile'; import { open } from 'fs/promises'; const file = await open('largefile.bin', 'r'); const buffer = Buffer.alloc(512); const { bytesRead } = await file.read(buffer, 0, 512, 0); await file.close(); const isBinary = await isBinaryFile(buffer, { size: bytesRead }); ``` -------------------------------- ### Check Binary with Specific Encoding Detection Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Dynamically determine the encoding hint based on a file's prefix and then use `isBinaryFileSync` with that hint. This example maps prefixes like 'german_' to 'latin1'. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const encodings = { 'german_': 'latin1', 'chinese_': 'big5', 'japanese_': 'shift-jis' }; function check(file: string) { const encoding = Object.entries(encodings) .find(([prefix]) => file.startsWith(prefix))?.[1]; return isBinaryFileSync(file, { encoding: encoding as any }); } ``` -------------------------------- ### Handle Non-UTF-8 Encodings with Sync Function Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/README.md This example shows how to specify an encoding hint when using the synchronous function `isBinaryFileSync` to correctly detect binary files with non-UTF-8 encodings. ```typescript const isBinary = isBinaryFileSync('file.txt', { encoding: 'big5' }); ``` -------------------------------- ### Avoid Practice: Use Generic CJK When Specific Known Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This example shows an anti-pattern: using a generic 'cjk' hint when a specific encoding is known. ```typescript // ✗ AVOID - Generic CJK when specific encoding is known isBinaryFileSync('file.txt', { encoding: 'cjk' }); ``` -------------------------------- ### Avoid Practice: Guessing CJK Encoding Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This example shows an anti-pattern: guessing at a CJK encoding which might be incorrect. ```typescript // ✗ AVOID - Guessing at CJK encoding isBinaryFileSync('asian-file.txt', { encoding: 'gb2312' }); // Maybe not correct ``` -------------------------------- ### Basic Usage of isbinaryfile Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/OVERVIEW.md Demonstrates asynchronous and synchronous file checking with isbinaryfile. Includes checking by path, by Buffer, and with an encoding hint. ```typescript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // Async - check file by path const isBinary = await isBinaryFile('file.pdf'); // Sync - check Buffer const buffer = readFileSync('image.gif'); const result = isBinaryFileSync(buffer); // With encoding hint const utf16File = await isBinaryFile('document.txt', { encoding: 'utf-16' }); ``` -------------------------------- ### Detect PDF Signature Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/DETECTION-ALGORITHM.md Identifies PDF files by checking for the '%PDF-' magic bytes at the start of the file. PDFs are considered binary. ```typescript if (totalBytes >= 5 && fileBuffer.slice(0, 5).toString() === '%PDF-') { return true; } ``` -------------------------------- ### Main Entry Point Imports Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/OVERVIEW.md Imports the primary functions and types from the 'isbinaryfile' package for general use. ```typescript import { isBinaryFile, isBinaryFileSync, EncodingHint } from 'isbinaryfile'; ``` -------------------------------- ### Import Legacy System Files Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This scenario shows how to import files from a legacy system that uses Latin-1 encoding for all text files, distinguishing between text and binary files. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { readFileSync } from 'fs'; function importLegacyFiles(directory: string) { const files = readdirSync(directory); const results = { text: [], binary: [], errors: [] }; for (const file of files) { try { // Legacy system uses Latin-1 for all text files const isText = !isBinaryFileSync(`${directory}/${file}`, { encoding: 'latin1' }); if (isText) { const content = readFileSync(`${directory}/${file}`, 'latin1'); results.text.push({ file, lines: content.split('\n').length }); } else { results.binary.push(file); } } catch (error) { results.errors.push({ file, error: error.message }); } } return results; } ``` -------------------------------- ### Multiple files with encoding hints Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfilesync.md Check multiple files for binary content while providing encoding hints to isBinaryFileSync. This improves accuracy for non-UTF-8 files. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const files = [ { path: 'doc1.txt', encoding: 'utf-16' }, { path: 'doc2.txt', encoding: 'latin1' }, { path: 'doc3.txt', encoding: 'euc-kr' } ]; for (const file of files) { const isBinary = isBinaryFileSync(file.path, { encoding: file.encoding }); console.log(`${file.path}: ${isBinary ? 'binary' : 'text'}`); } ``` -------------------------------- ### Index Content Management System Files Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This scenario demonstrates indexing files in a CMS that supports multiple languages with different encodings, using async detection. ```typescript import { isBinaryFile } from 'isbinaryfile'; import { readdirSync } from 'fs'; async function indexCMSContent(contentDir: string) { // CMS supports multiple languages with different encodings const encodingMap = new Map([ ['.ja', 'shift-jis'], ['.zh', 'big5'], ['.ko', 'euc-kr'], ['.de', 'latin1'], ]); const files = readdirSync(contentDir); const indexed = []; for (const file of files) { const ext = file.substring(file.lastIndexOf('.')); const encoding = encodingMap.get(ext); try { const isBinary = await isBinaryFile(`${contentDir}/${file}`, { encoding: encoding as any }); indexed.push({ file, encoding: encoding || 'utf-8', type: isBinary ? 'binary' : 'text' }); } catch (error) { console.error(`Failed to index ${file}:`, error.message); } } return indexed; } ``` -------------------------------- ### Encoding Hints Source: https://github.com/gjtorikian/isbinaryfile/blob/main/README.md Provides guidance on using encoding hints for accurate binary detection in files with non-UTF-8 encodings. ```APIDOC ## Encoding Hints For files that use non-UTF-8 encodings, you can provide encoding hints to improve detection accuracy. ### Usage with Options ```javascript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // UTF-16 files without BOM are auto-detected in most cases const result1 = await isBinaryFile('utf16-file.txt'); // Or provide explicit encoding hint const result2 = await isBinaryFile('utf16-file.txt', { encoding: 'utf-16' }); // ISO-8859-1 / Latin-1 encoded files const result3 = isBinaryFileSync('german-text.txt', { encoding: 'latin1' }); // CJK encoded files (Big5, GB2312, EUC-KR, etc.) const result4 = isBinaryFileSync('chinese-big5.txt', { encoding: 'big5' }); const result5 = isBinaryFileSync('korean-text.txt', { encoding: 'euc-kr' }); // Generic CJK hint when exact encoding is unknown const result6 = isBinaryFileSync('asian-text.txt', { encoding: 'cjk' }); ``` ### Supported Encoding Hints | Hint | Description | | ------------ | ------------------------------------------ | | `utf-16` | UTF-16 (auto-detect endianness) | | `utf-16le` | UTF-16 Little Endian | | `utf-16be` | UTF-16 Big Endian | | `latin1` | ISO-8859-1 / Latin-1 | | `iso-8859-1` | Alias for latin1 | | `cjk` | Generic CJK (use when encoding is unknown) | | `big5` | Traditional Chinese | | `gb2312` | Simplified Chinese | | `gbk` | Extended GB2312 | | `euc-kr` | Korean | | `shift-jis` | Japanese | **Note:** UTF-16 without BOM is automatically detected in most cases without needing a hint. ``` -------------------------------- ### Handle Path Not a File Error (Async and Sync) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Demonstrates how to catch the custom 'Path provided was not a file!' error when using isBinaryFile or isBinaryFileSync with a directory path. ```typescript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // Async try { await isBinaryFile('/path/to/directory/'); } catch (error) { console.error(error.message); // "Path provided was not a file!" } // Sync try { isBinaryFileSync('/path/to/directory/'); } catch (error) { console.error(error.message); // "Path provided was not a file!" } ``` -------------------------------- ### Encoding Hints for Non-UTF-8 Files Source: https://github.com/gjtorikian/isbinaryfile/blob/main/README.md Shows how to provide encoding hints to isBinaryFile and isBinaryFileSync for accurate detection of files with specific non-UTF-8 encodings like UTF-16, Latin-1, and various CJK encodings. ```javascript import { isBinaryFile, isBinaryFileSync } from 'isbinaryfile'; // UTF-16 files without BOM are auto-detected in most cases const result1 = await isBinaryFile('utf16-file.txt'); // Or provide explicit encoding hint const result2 = await isBinaryFile('utf16-file.txt', { encoding: 'utf-16' }); // ISO-8859-1 / Latin-1 encoded files const result3 = isBinaryFileSync('german-text.txt', { encoding: 'latin1' }); // CJK encoded files (Big5, GB2312, EUC-KR, etc.) const result4 = isBinaryFileSync('chinese-big5.txt', { encoding: 'big5' }); const result5 = isBinaryFileSync('korean-text.txt', { encoding: 'euc-kr' }); // Generic CJK hint when exact encoding is unknown const result6 = isBinaryFileSync('asian-text.txt', { encoding: 'cjk' }); ``` -------------------------------- ### Check a file by path (async/await) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfile.md Use this snippet to check if a file is binary by providing its path. It returns a Promise that resolves to a boolean. ```typescript import { isBinaryFile } from 'isbinaryfile'; const isBinary = await isBinaryFile('path/to/file.pdf'); if (isBinary) { console.log('File is binary'); } else { console.log('File is text'); } ``` -------------------------------- ### Check file with extension-based encoding hints Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Determine if a file is binary by using encoding hints derived from its file extension. A mapping from common extensions to specific encodings is used to provide the hint to isBinaryFileSync. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const extToEncoding = { '.ja': 'shift-jis', '.zh': 'big5', '.ko': 'euc-kr', '.de': 'latin1', } as Record; function checkFile(path: string) { const ext = path.substring(path.lastIndexOf('.')); const encoding = extToEncoding[ext]; return isBinaryFileSync(path, { encoding }); } ``` -------------------------------- ### Verify UTF-16 Detection with isBinaryFileSync Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/encoding-module.md Shows how to use the detected UTF-16 encoding from detectUtf16NoBom with isBinaryFileSync for further validation. Ensure the buffer and bytesRead are correctly provided. ```typescript import { detectUtf16NoBom, isBinaryFileSync } from 'isbinaryfile'; import { readFileSync } from 'fs'; const buffer = readFileSync('document.txt'); const encoding = detectUtf16NoBom(buffer, 512); if (encoding) { // Validate as text using detected encoding const isBinary = isBinaryFileSync(buffer, { encoding }); console.log(`Is binary: ${isBinary}`); } ``` -------------------------------- ### Process Multilingual Directory Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This scenario demonstrates processing files in a directory with mixed languages and encodings by dynamically determining the encoding for each file. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { readdirSync } from 'fs'; const encodings = { 'german_': 'latin1', 'chinese_': 'cjk', 'korean_': 'euc-kr', 'japanese_': 'shift-jis', }; function getEncoding(filename: string): string | undefined { for (const [prefix, encoding] of Object.entries(encodings)) { if (filename.startsWith(prefix)) { return encoding; } } return undefined; } const files = readdirSync('./texts'); for (const file of files) { const encoding = getEncoding(file); const isBinary = isBinaryFileSync(`./texts/${file}`, { encoding: encoding as any }); console.log(`${file}: ${isBinary ? 'BINARY' : 'TEXT'}`); } ``` -------------------------------- ### Batch Process Files Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Iterate through a list of files obtained from `readdirSync` and use `isBinaryFileSync` to determine if each file is binary, logging the result. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { readdirSync } from 'fs'; const files = readdirSync('./'); for (const file of files) { const isBinary = isBinaryFileSync(file); console.log(`${file}: ${isBinary ? 'BINARY' : 'TEXT'}`); } ``` -------------------------------- ### Handle EACCES: Permission Denied Error Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Shows how to catch the 'EACCES' error when isBinaryFileSync is called on a file without read permissions. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; try { isBinaryFileSync('/root/protected.txt'); } catch (error) { if (error.code === 'EACCES') { console.log('Permission denied: cannot read file'); } } ``` -------------------------------- ### Process File with Encoding Detection (Async) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/OVERVIEW.md Asynchronously checks if a file is binary, optionally providing an encoding hint. Skips processing if the file is detected as binary. Requires 'isbinaryfile' import. ```typescript import { isBinaryFile } from 'isbinaryfile'; async function processFile(path: string, encoding?: string) { const isBinary = await isBinaryFile(path, { encoding: encoding as any }); if (isBinary) { console.log('Skipping binary file'); } else { // Process as text } } ``` -------------------------------- ### Auto-detect UTF-16 File Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/encoding-module.md Demonstrates how to use detectUtf16NoBom to identify the endianness of a UTF-16 encoded file that lacks a BOM. Requires importing the function and reading the file into a buffer. ```typescript import { detectUtf16NoBom } from 'isbinaryfile'; import { readFileSync } from 'fs'; const buffer = readFileSync('utf16-file.txt'); const detected = detectUtf16NoBom(buffer, buffer.length); if (detected === 'utf-16le') { console.log('Detected UTF-16 Little Endian'); } else if (detected === 'utf-16be') { console.log('Detected UTF-16 Big Endian'); } else { console.log('UTF-16 without BOM not detected'); } ``` -------------------------------- ### Combine Encoding Detection with File Extension Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md This snippet shows how to determine the encoding hint based on a file's extension, then use it with isBinaryFileSync. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; function getEncodingFromExtension(filename: string): string | undefined { const ext = filename.substring(filename.lastIndexOf('.')).toLowerCase(); const extMap = { '.ja': 'shift-jis', '.zh': 'big5', '.ko': 'euc-kr', '.de': 'latin1', '.es': 'latin1', }; return extMap[ext as keyof typeof extMap]; } function checkFile(path: string) { const encoding = getEncodingFromExtension(path); return isBinaryFileSync(path, { encoding: encoding as any }); } ``` -------------------------------- ### Check multiple files with fallback encoding Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Iterate through a list of files and encoding hints, attempting to determine if each file is binary. The loop breaks on the first successful check (no error thrown) for a given file. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const files = ['file1.txt', 'file2.txt']; const hints = ['latin1', 'utf-16', 'big5']; for (const file of files) { for (const hint of hints) { try { const isBinary = isBinaryFileSync(file, { encoding: hint as any }); console.log(`${file} (${hint}): ${isBinary}`); break; // Stop if no error } catch (e) { // Try next hint } } } ``` -------------------------------- ### Safely Check File with Try-Catch Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md Use this pattern to handle potential errors like file not found or invalid path when checking if a file is binary. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; function safeCheckFile(path: string, encoding: string): boolean | null { try { return isBinaryFileSync(path, { encoding: encoding as any }); } catch (error) { if (error.code === 'ENOENT') { console.log(`File not found: ${path}`); } else if (error.message === 'Path provided was not a file!') { console.log(`Not a file: ${path}`); } else { console.error(`Error: ${error.message}`); } return null; } } ``` -------------------------------- ### Async Error Handling with Promise.catch() Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Use this snippet to handle potential file system errors when checking if a file is binary asynchronously. It specifically catches 'ENOENT' for non-existent files and errors indicating a directory was provided instead of a file. ```typescript import { isBinaryFile } from 'isbinaryfile'; isBinaryFile('file.txt') .then((isBinary) => { console.log(`Binary: ${isBinary}`); }) .catch((error) => { if (error.code === 'ENOENT') { console.log('File not found'); } else if (error.message === 'Path provided was not a file!') { console.log('This is a directory, not a file'); } }); ``` -------------------------------- ### isBinaryFile(filepath[, options]) - Async File Path Source: https://github.com/gjtorikian/isbinaryfile/blob/main/README.md Asynchronously checks if a file at the given filepath is binary. Returns a Promise that resolves to a boolean. ```APIDOC ## isBinaryFile(filepath[, options]) ### Description Asynchronously detects if a file is binary by reading its content. ### Method `isBinaryFile` ### Parameters #### Path Parameters - **filepath** (string) - Required - The path to the file to check. #### Query Parameters - **options** (object) - Optional - Configuration options. - **encoding** (string) - Optional - An encoding hint for non-UTF-8 files (e.g., 'utf-16', 'latin1', 'cjk'). ### Response #### Success Response (Promise) - **boolean** - `true` if the file is binary, `false` otherwise. ### Request Example ```javascript import { isBinaryFile } from 'isbinaryfile'; const filename = 'fixtures/pdf.pdf'; const result = await isBinaryFile(filename); if (result) { console.log('It is binary!'); } else { console.log('No it is not.'); } ``` ``` -------------------------------- ### Using encoding hints for non-UTF-8 files Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfile.md Provide an 'encoding' hint to improve detection accuracy for non-UTF-8 files. This is useful for files encoded in UTF-16, Big5, or Latin-1. ```typescript import { isBinaryFile } from 'isbinaryfile'; // UTF-16 encoded file const utf16File = await isBinaryFile('document.txt', { encoding: 'utf-16' }); // Big5-encoded Chinese text const chineseFile = await isBinaryFile('chinese.txt', { encoding: 'big5' }); // Latin-1 encoded document const latinFile = await isBinaryFile('document.txt', { encoding: 'latin1' }); ``` -------------------------------- ### Use Both Encoding and Size Options Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Combine the `encoding` and `size` options when checking a Buffer to provide both character set hints and specify the scan size. ```typescript isBinaryFileSync(buffer, { encoding: 'utf-16', size: 256 }); ``` -------------------------------- ### Process Files in Parallel (Async) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Use `Promise.all` with `isBinaryFile` to concurrently check multiple files for binary content. This is more efficient than sequential checks for I/O-bound operations. ```typescript import { isBinaryFile } from 'isbinaryfile'; const files = ['file1.txt', 'file2.pdf', 'file3.js']; const results = await Promise.all(files.map(f => isBinaryFile(f))); ``` -------------------------------- ### isBinaryFile (Async) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/README.md Asynchronously detects if a file is binary. It reads a portion of the file to determine its nature. Supports options for encoding hints to improve accuracy for non-UTF-8 files. ```APIDOC ## isBinaryFile (Async) ### Description Asynchronously detects if a file is binary. It reads a portion of the file to determine its nature. Supports options for encoding hints to improve accuracy for non-UTF-8 files. ### Method `async` ### Signature `isBinaryFile(file: string | Buffer, options?: IsBinaryOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (Options) `options` (IsBinaryOptions) - Optional. An object to provide additional hints for detection. - **encoding** (EncodingHint) - Optional. Specifies the file's encoding if it's not UTF-8. Supported values include various UTF-16 variants, Latin-1, and CJK encodings. - **size** (number) - Optional. Specifies the number of bytes to read for detection. Defaults to 512. ### Request Example ```typescript import { isBinaryFile } from 'isbinaryfile'; const isBinary = await isBinaryFile('file.pdf'); const isBinaryWithEncoding = await isBinaryFile('file.txt', { encoding: 'big5' }); ``` ### Response #### Success Response - **boolean**: `true` if the file is detected as binary, `false` if it is detected as text or empty. #### Response Example ```json true ``` #### Error Handling - Throws an error if the file cannot be accessed (e.g., `ENOENT`). ``` -------------------------------- ### Check a file by path (synchronous) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfilesync.md Use isBinaryFileSync to check if a file at a given path is binary. This is a direct synchronous check. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const isBinary = isBinaryFileSync('path/to/file.pdf'); if (isBinary) { console.log('File is binary'); } else { console.log('File is text'); } ``` -------------------------------- ### Buffer Input (No File System Errors) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md When providing a Buffer directly to isBinaryFileSync, file system errors are not encountered. This is useful for checking binary content without interacting with the file system. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const buffer = Buffer.from([0x00, 0x01, 0x02, 0x03]); // Null byte present const result = isBinaryFileSync(buffer); // Returns true, no errors thrown ``` -------------------------------- ### isBinaryFileSync Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfilesync.md Synchronous version of `isBinaryFile`. Detects whether a file is binary or text using the same algorithm as the async version. Reads the first 512 bytes of the file and analyzes for binary indicators without using promises or callbacks. Returns `true` if the file appears binary, `false` if it appears to be text. ```APIDOC ## isBinaryFileSync ### Description Synchronous version of `isBinaryFile`. Detects whether a file is binary or text using the same algorithm as the async version. Reads the first 512 bytes of the file and analyzes for binary indicators without using promises or callbacks. Returns `true` if the file appears binary, `false` if it appears to be text. ### Function Signature ```typescript export function isBinaryFileSync( file: string | Buffer, options?: IsBinaryOptions ): boolean ``` ### Parameters #### Path Parameters - **file** (string | Buffer) - Required - File path as a string, or Buffer containing file contents #### Query Parameters - **options** (IsBinaryOptions) - Optional - Optional detection parameters - **encoding** (EncodingHint) - Optional - Hint about expected file encoding to improve detection accuracy for non-UTF-8 files - **size** (number) - Optional - Byte limit to scan when analyzing a Buffer. If not provided, defaults to Buffer length. Only used when `file` is a Buffer ### Return Value `boolean` - `true`: File is detected as binary - `false`: File is detected as text or is empty ### Throws - `Error("Path provided was not a file!")`: When the file path points to a directory - `Error` (from Node.js fs): When file does not exist or cannot be read (e.g., ENOENT, EACCES) ### Examples #### Check a file by path (synchronous) ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const isBinary = isBinaryFileSync('path/to/file.pdf'); if (isBinary) { console.log('File is binary'); } else { console.log('File is text'); } ``` #### Check a Buffer without size parameter ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { readFileSync } from 'fs'; const buffer = readFileSync('image.gif'); const result = isBinaryFileSync(buffer); console.log(result); // true for .gif files ``` #### With explicit size parameter ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { openSync, readSync, closeSync } from 'fs'; const fd = openSync('largefile.bin', 'r'); const buffer = Buffer.alloc(512); const bytesRead = readSync(fd, buffer, 0, 512, 0); closeSync(fd); const isBinary = isBinaryFileSync(buffer, { size: bytesRead }); ``` #### Multiple files with encoding hints ```typescript import { isBinaryFileSync } from 'isbinaryfile'; const files = [ { path: 'doc1.txt', encoding: 'utf-16' }, { path: 'doc2.txt', encoding: 'latin1' }, { path: 'doc3.txt', encoding: 'euc-kr' } ]; for (const file of files) { const isBinary = isBinaryFileSync(file.path, { encoding: file.encoding }); console.log(`${file.path}: ${isBinary ? 'binary' : 'text'}`); } ``` #### Error handling ```typescript import { isBinaryFileSync } from 'isbinaryfile'; try { const result = isBinaryFileSync('path/to/file'); } catch (error) { if (error.message === 'Path provided was not a file!') { console.log('Expected a file, got a directory'); } else if (error.code === 'ENOENT') { console.log('File not found'); } else { console.log('Unexpected error:', error.message); } } ``` ``` -------------------------------- ### Process CJK Files Without Exact Encoding (Sync) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/encoding-module.md Demonstrates using `isBinaryFileSync` with an 'cjk' encoding hint when the exact encoding of a file is unknown. This snippet shows how to conditionally process the file as text if it's not detected as binary. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; // Using generic CJK hint when exact encoding is unknown const isText = isBinaryFileSync('chinese-file.txt', { encoding: 'cjk' }); if (!isText) { // Process as text file } ``` -------------------------------- ### Recover from EACCES: Permission Denied Error Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Illustrates checking for read permissions with fs.accessSync before calling isBinaryFileSync to avoid 'EACCES' errors. ```typescript import { accessSync, constants } from 'fs'; import { isBinaryFileSync } from 'isbinaryfile'; const path = '/path/to/file.txt'; try { accessSync(path, constants.R_OK); const result = isBinaryFileSync(path); } catch { console.log('File is not readable'); } ``` -------------------------------- ### isbinaryfile Return Values Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md The `isbinaryfile` functions return `true` if the file is determined to be binary, and `false` if it is text or empty. ```typescript true // File is binary false // File is text or empty ``` -------------------------------- ### Specify Encoding Hint for isbinaryfile Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Provide an encoding hint to `isBinaryFileSync` to improve detection accuracy for specific character sets. Supported hints include 'utf-16', 'latin1', and various CJK encodings. ```typescript // UTF-16 isBinaryFileSync('file.txt', { encoding: 'utf-16' }); // Latin-1 isBinaryFileSync('file.txt', { encoding: 'latin1' }); // CJK (Big5, GB2312, GBK, EUC-KR, Shift-JIS) isBinaryFileSync('file.txt', { encoding: 'big5' }); isBinaryFileSync('file.txt', { encoding: 'gb2312' }); isBinaryFileSync('file.txt', { encoding: 'euc-kr' }); ``` -------------------------------- ### Process Multiple Files Concurrently Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/README.md This snippet illustrates how to process multiple files concurrently to check if they are binary. It uses `Promise.all` with the asynchronous `isBinaryFile` function for efficient I/O operations. ```typescript const files = ['a.txt', 'b.pdf', 'c.js']; const results = await Promise.all(files.map(f => isBinaryFile(f))); ``` -------------------------------- ### Check if a File is Binary (Sync) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Synchronously determine if a file at the given path is binary. This will block the event loop. ```typescript const isBinary = isBinaryFileSync('path/to/file.txt'); ``` -------------------------------- ### Async Error Handling with Try-Catch Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md A function demonstrating comprehensive async error handling for isBinaryFile, catching specific custom errors and Node.js file system errors. ```typescript import { isBinaryFile } from 'isbinaryfile'; async function checkFile(path: string): Promise { try { return await isBinaryFile(path); } catch (error) { if (error.message === 'Path provided was not a file!') { console.log('Expected a file, not a directory'); } else if (error.code === 'ENOENT') { console.log('File does not exist'); } else if (error.code === 'EACCES') { console.log('Permission denied'); } else { console.error(`Unexpected error: ${error.message}`); } return null; } } ``` -------------------------------- ### Handling Empty Files in Binary Detection Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/DETECTION-ALGORITHM.md Considers empty files (0 bytes) as text, returning false. This aligns with Perl's -B convention. ```typescript if (bytesRead === 0) { return false; // Empty files are considered text } ``` -------------------------------- ### Troubleshoot Text File Detected as Binary Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md When a text file is incorrectly identified as binary, try applying an encoding hint. If the issue persists, inspect null bytes and verify the encoding. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; // Try with encoding hint const result = isBinaryFileSync('file.txt', { encoding: 'cjk' }); if (result === true) { // 1. Check for null bytes (use hexdump or similar) // 2. Verify encoding is correct // 3. Try different encoding in 'cjk' family } ``` -------------------------------- ### Handle Errors with Try-Catch (Async) Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md Use a try-catch block to handle potential errors when calling the asynchronous `isBinaryFile` function. Common errors include 'ENOENT' (file not found) and 'Path provided was not a file!' (if a directory path is given). ```typescript try { const isBinary = await isBinaryFile('file.txt'); } catch (error) { if (error.code === 'ENOENT') console.log('File not found'); else if (error.message === 'Path provided was not a file!') console.log('Is directory'); } ``` -------------------------------- ### Specify Buffer Size for isbinaryfile Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/QUICK-REFERENCE.md When checking a Buffer, specify the `size` option to indicate how many bytes of the buffer should be scanned. This is useful when you have read only a portion of a file into a buffer. ```typescript const buffer = Buffer.alloc(512); const bytesRead = readSync(fd, buffer, 0, 512, 0); isBinaryFileSync(buffer, { size: bytesRead }); ``` -------------------------------- ### Check a Buffer with explicit size parameter Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfilesync.md Analyze a Buffer for binary content up to a specified size using isBinaryFileSync. This is useful for optimizing analysis on large Buffers. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { openSync, readSync, closeSync } from 'fs'; const fd = openSync('largefile.bin', 'r'); const buffer = Buffer.alloc(512); const bytesRead = readSync(fd, buffer, 0, 512, 0); closeSync(fd); const isBinary = isBinaryFileSync(buffer, { size: bytesRead }); ``` -------------------------------- ### Error handling Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfile.md This snippet shows how to handle potential errors when using isBinaryFile, such as when the path is not a file or the file does not exist. ```typescript import { isBinaryFile } from 'isbinaryfile'; try { const result = await isBinaryFile('path/to/file'); } catch (error) { if (error.message === 'Path provided was not a file!') { console.log('Expected a file, got a directory'); } else if (error.code === 'ENOENT') { console.log('File not found'); } } ``` -------------------------------- ### Provide Encoding Hint for Non-UTF-8 Files Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/README.md When a file uses a non-UTF-8 encoding, provide an encoding hint to improve the accuracy of binary detection. Supported encodings include UTF-16 variants, Latin-1, and several CJK encodings. ```typescript isBinaryFileSync('file.txt', { encoding: 'big5' }); ``` -------------------------------- ### Handle ENOENT: File Not Found Error Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Illustrates catching the 'ENOENT' error when isBinaryFileSync is called with a path that does not exist. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; try { isBinaryFileSync('/nonexistent/file.txt'); } catch (error) { console.error(error.code); // 'ENOENT' console.error(error.message); // Details about missing file } ``` -------------------------------- ### Check a Buffer Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfile.md This snippet demonstrates how to check if a Buffer contains binary data. Ensure the Buffer is populated with file content before passing it to isBinaryFile. ```typescript import { isBinaryFile } from 'isbinaryfile'; import { readFile } from 'fs/promises'; const buffer = await readFile('document.docx'); const result = await isBinaryFile(buffer); ``` -------------------------------- ### Batch Process Files Synchronously Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/OVERVIEW.md Iterates through files in a directory and checks if each is binary using the synchronous function. Requires 'fs' and 'isbinaryfile' imports. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; import { readdirSync } from 'fs'; const files = readdirSync('./src'); for (const file of files) { const isBinary = isBinaryFileSync(`./src/${file}`); console.log(`${file}: ${isBinary ? 'binary' : 'text'}`); } ``` -------------------------------- ### Recover from Path Not a File Error Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Shows how to check if an entry is a file using fs.statSync before calling isBinaryFileSync to avoid the 'Path provided was not a file!' error. ```typescript import { statSync } from 'fs'; import { isBinaryFileSync } from 'isbinaryfile'; const path = '/path/to/entry/'; const stat = statSync(path); if (stat.isFile()) { const result = isBinaryFileSync(path); // ... } else if (stat.isDirectory()) { console.log('Entry is a directory, not a file'); // Handle directory separately } ``` -------------------------------- ### Parallel Async File Processing Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/OVERVIEW.md Uses glob to find files and then processes them in parallel using Promise.all to check if each is binary. Requires 'isbinaryfile' and 'glob' imports. ```typescript import { isBinaryFile } from 'isbinaryfile'; import { glob } from 'glob'; const files = await glob('./src/**/*'); const results = await Promise.all( files.map(file => isBinaryFile(file)) ); files.forEach((file, i) => { console.log(`${file}: ${results[i] ? 'binary' : 'text'}`); }); ``` -------------------------------- ### Recover from ENOENT: File Not Found Error Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/errors.md Demonstrates checking for file existence with fs.existsSync before calling isBinaryFileSync to prevent 'ENOENT' errors. ```typescript import { existsSync } from 'fs'; import { isBinaryFileSync } from 'isbinaryfile'; const path = '/path/to/file.txt'; if (existsSync(path)) { const result = isBinaryFileSync(path); } else { console.log('File does not exist'); } ``` -------------------------------- ### Error handling for isBinaryFileSync Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfilesync.md Implement error handling for isBinaryFileSync to gracefully manage exceptions like invalid paths or file access issues. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; try { const result = isBinaryFileSync('path/to/file'); } catch (error) { if (error.message === 'Path provided was not a file!') { console.log('Expected a file, got a directory'); } else if (error.code === 'ENOENT') { console.log('File not found'); } else { console.log('Unexpected error:', error.message); } } ``` -------------------------------- ### isBinaryFile Function Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/api-reference/isbinaryfile.md Detects whether a file is binary or text using an algorithm similar to Perl's `-B` switch. It analyzes the first 512 bytes of the file for null bytes, non-ASCII characters, control sequences, UTF-8 patterns, and known binary formats. Returns `true` if the file appears binary, `false` otherwise. ```APIDOC ## isBinaryFile(file: string | Buffer, options?: IsBinaryOptions): Promise ### Description Detects whether a file is binary or text. Reads the first 512 bytes of the file and analyzes for null bytes, non-ASCII characters, control sequences, UTF-8 multi-byte sequences, known binary formats, and encoding-specific patterns. ### Method `async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **file** (string | Buffer) - Required - File path as a string, or Buffer containing file contents. - **options** (IsBinaryOptions) - Optional - Optional detection parameters. - **options.encoding** (EncodingHint) - Optional - Hint about expected file encoding to improve detection accuracy for non-UTF-8 files. - **options.size** (number) - Optional - Byte limit to scan when analyzing a Buffer. If not provided, defaults to Buffer length. Only used when `file` is a Buffer. ### Request Example ```typescript import { isBinaryFile } from 'isbinaryfile'; // Check a file by path (async/await) const isBinary = await isBinaryFile('path/to/file.pdf'); if (isBinary) { console.log('File is binary'); } else { console.log('File is text'); } // Check a Buffer import { readFile } from 'fs/promises'; const buffer = await readFile('document.docx'); const result = await isBinaryFile(buffer); // With explicit size parameter for partial reads import { open } from 'fs/promises'; const file = await open('largefile.bin', 'r'); const readBuffer = Buffer.alloc(512); const { bytesRead } = await file.read(readBuffer, 0, 512, 0); await file.close(); const isBinaryPartial = await isBinaryFile(readBuffer, { size: bytesRead }); // Using encoding hints for non-UTF-8 files const utf16File = await isBinaryFile('document.txt', { encoding: 'utf-16' }); const chineseFile = await isBinaryFile('chinese.txt', { encoding: 'big5' }); const latinFile = await isBinaryFile('document.txt', { encoding: 'latin1' }); ``` ### Response #### Success Response `Promise` - `true`: File is detected as binary. - `false`: File is detected as text or is empty. #### Response Example ```json true ``` ### Throws - `Error("Path provided was not a file!")`: When the file path points to a directory. - `Error` (from Node.js fs): When file does not exist or cannot be read (e.g., ENOENT, EACCES). ``` -------------------------------- ### Detect Unknown CJK (Generic) File Source: https://github.com/gjtorikian/isbinaryfile/blob/main/_autodocs/ENCODING-HINTS-GUIDE.md Use this snippet when the exact CJK encoding is unknown, falling back to a generic 'cjk' hint. ```typescript import { isBinaryFileSync } from 'isbinaryfile'; // When exact CJK encoding is unknown const isText = isBinaryFileSync('mystery.txt', { encoding: 'cjk' }); ```