### Initialize SonicBoom with options Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Example demonstrating how to instantiate a SonicBoom object using a configuration object. ```javascript const opts = { dest: './app.log', minLength: 4096, maxLength: 1048576, append: true, mkdir: true, contentMode: 'utf8' }; const sonic = new SonicBoom(opts); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Demonstrates initializing a SonicBoom instance and writing data to a file descriptor. ```javascript 'use strict' const SonicBoom = require('sonic-boom') const sonic = new SonicBoom({ fd: process.stdout.fd }) // or { dest: '/path/to/destination' } for (let i = 0; i < 10; i++) { sonic.write('hello sonic\n') } ``` -------------------------------- ### SonicBoom Usage Examples Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Demonstrates various initialization patterns including writing to file descriptors, file paths with buffering, synchronous mode, and binary buffer mode. ```javascript const SonicBoom = require('sonic-boom'); // Write to file descriptor (stdout) const sonic = new SonicBoom({ fd: process.stdout.fd }); sonic.write('Hello\n'); // Write to file path with buffering const logStream = new SonicBoom({ dest: '/var/log/app.log', minLength: 4096, append: true }); logStream.write('Application started\n'); // Synchronous mode (like console.log) const syncStream = new SonicBoom({ dest: './debug.log', sync: true }); // Buffer mode for binary data const bufferStream = new SonicBoom({ dest: './data.bin', contentMode: 'buffer' }); bufferStream.write(Buffer.from([0x01, 0x02, 0x03])); ``` -------------------------------- ### Initialize and write to a file with Sonic-Boom Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/00-START-HERE.txt Basic setup for creating a SonicBoom instance and writing data to a destination file. ```javascript const SonicBoom = require('sonic-boom'); const sonic = new SonicBoom({ dest: './app.log' }); sonic.write('Hello World\n'); sonic.end(); ``` -------------------------------- ### Install Sonic Boom Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Command to install the package via npm. ```bash npm i sonic-boom ``` -------------------------------- ### Implement RetryEAGAIN callback Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Example implementation of the retryEAGAIN callback within the SonicBoom constructor options. ```javascript const sonic = new SonicBoom({ dest: './app.log', retryEAGAIN: (err, writeBufferLen, remainingBufferLen) => { console.log(`EAGAIN: ${writeBufferLen} bytes failed, ${remainingBufferLen} remaining`); return true; // Always retry } }); ``` -------------------------------- ### Catching constructor option errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/errors.md Examples of handling validation errors for invalid constructor arguments, including missing destinations, invalid buffer sizes, and unsupported content modes. ```javascript try { const sonic = new SonicBoom({}); // No fd or dest } catch (err) { if (err.message === 'SonicBoom supports only file descriptors and files') { console.log('Must provide fd or dest option'); } } ``` ```javascript try { const sonic = new SonicBoom({ dest: './app.log', minLength: 20000, // Invalid: exceeds maxWrite (16384) maxWrite: 16384 }); } catch (err) { if (err.message.includes('minLength should be smaller than maxWrite')) { console.log('Invalid minLength configuration'); } } ``` ```javascript try { const sonic = new SonicBoom({ dest: './app.log', contentMode: 'json' // Invalid }); } catch (err) { if (err.message.includes('SonicBoom supports "utf8" and "buffer"')) { console.log('Invalid contentMode:', err.message); } } ``` -------------------------------- ### constructor(opts: SonicBoomOpts) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Initializes a new SonicBoom instance with the provided configuration options. ```APIDOC ## constructor ### Description Creates a new instance of SonicBoom. ### Signature `new SonicBoom(opts: SonicBoomOpts)` ### Parameters - **opts** (SonicBoomOpts) - Required - Configuration object for the instance. ``` -------------------------------- ### Basic Logging Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Initialize a SonicBoom instance with a destination file and write data. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); sonic.write('log\n'); sonic.end(); ``` -------------------------------- ### Basic stream usage Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Initialize a stream to a file, write data, and handle lifecycle events. ```javascript const SonicBoom = require('sonic-boom'); // Write to file const sonic = new SonicBoom({ dest: './app.log' }); sonic.write('Hello World\n'); sonic.write('Another line\n'); sonic.on('error', (err) => { console.error('Write error:', err); }); sonic.on('close', () => { console.log('Stream closed'); }); sonic.end(); ``` -------------------------------- ### Configure content modes Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Switch between UTF-8 string mode and binary buffer mode. ```javascript const sonic = new SonicBoom({ dest: './app.log', contentMode: 'utf8' }); sonic.write('Hello\n'); // String ``` ```javascript const sonic = new SonicBoom({ dest: './data.bin', contentMode: 'buffer' }); sonic.write(Buffer.from([0x01, 0x02, 0x03])); // Buffer ``` -------------------------------- ### Configure ContentMode options Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Demonstrates initializing SonicBoom with different contentMode settings for string or buffer data. ```javascript // UTF-8 string mode (default) const sonic1 = new SonicBoom({ dest: './log.txt', contentMode: 'utf8' }); sonic1.write('Hello\n'); // Buffer mode const sonic2 = new SonicBoom({ dest: './data.bin', contentMode: 'buffer' }); sonic2.write(Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f])); ``` -------------------------------- ### High Performance Configuration Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Configure minLength and maxLength to optimize memory buffering for high-throughput scenarios. ```javascript const sonic = new SonicBoom({ dest: './app.log', minLength: 8192, maxLength: 1048576 }); ``` -------------------------------- ### Configure constructor destinations Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Specify output destination using file paths, file descriptors, or standard output. ```javascript // Write to file path new SonicBoom({ dest: './app.log' }) // Write to file descriptor const fd = require('fs').openSync('./app.log', 'a'); new SonicBoom({ fd }) // Write to stdout new SonicBoom({ fd: process.stdout.fd }) ``` -------------------------------- ### Catching sonic boom is not ready yet errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/errors.md Shows how to wait for the 'ready' event before performing synchronous flush operations to avoid readiness errors. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); sonic.on('ready', () => { try { sonic.flushSync(); } catch (err) { console.error('Sync flush error:', err); } }); ``` -------------------------------- ### SonicBoom(opts) Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Creates a new instance of SonicBoom with the specified configuration options. ```APIDOC ## SonicBoom(opts) ### Description Creates a new instance of SonicBoom for file writing. ### Parameters - **opts** (Object) - Required - Configuration options including fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, fsync, append, mode, contentMode, mkdir, and retryEAGAIN. ``` -------------------------------- ### Importing Sonic Boom Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Demonstrates the various ways to import the Sonic Boom module using CommonJS or ESM syntax. ```javascript const SonicBoom = require('sonic-boom'); // CommonJS default export const { SonicBoom } = require('sonic-boom'); // Named export also available import SonicBoom from 'sonic-boom'; // ESM default import ``` -------------------------------- ### Handle ready event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered when the stream is ready to accept writes. For synchronous mode, ensure the listener is attached before stream creation. ```javascript sonic.on('ready', () => { sonic.write('Stream is ready\n'); }); ``` -------------------------------- ### Initialize SonicBoom Instance Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Constructor signature for creating a new SonicBoom stream instance. ```javascript new SonicBoom(opts: SonicBoomOpts): SonicBoom ``` -------------------------------- ### SonicBoom(opts) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Creates a new SonicBoom instance for writing to files or file descriptors. The stream is ready when the 'ready' event is emitted or immediately in synchronous mode. ```APIDOC ## Constructor: SonicBoom(opts) ### Description Creates a new SonicBoom instance. The stream is ready when the 'ready' event is emitted or for synchronous mode, immediately. ### Parameters - **opts** (SonicBoomOpts) - Required - Configuration object - **opts.fd** (number | string) - Optional - File descriptor number or file path string. - **opts.dest** (string | number) - Optional - File path or file descriptor to write to. - **opts.minLength** (number) - Optional - Minimum buffer length before flushing to disk. - **opts.maxLength** (number) - Optional - Maximum buffer length allowed. - **opts.maxWrite** (number) - Optional - Maximum bytes written per fs.write() call. - **opts.periodicFlush** (number) - Optional - Interval in milliseconds for periodic flushing. - **opts.sync** (boolean) - Optional - If true, performs synchronous writes. - **opts.fsync** (boolean) - Optional - If true, performs fs.fsyncSync() after each write. - **opts.append** (boolean) - Optional - If true, appends to file. - **opts.mode** (string | number) - Optional - File creation mode. - **opts.mkdir** (boolean) - Optional - If true, creates parent directories recursively. - **opts.contentMode** ('utf8' | 'buffer') - Optional - Content type: 'utf8' for strings, 'buffer' for Buffer objects. - **opts.retryEAGAIN** (function) - Optional - Custom retry handler for EAGAIN/EBUSY errors. ### Returns - **SonicBoom** (Instance) - A new SonicBoom instance (extends EventEmitter). ### Request Example ```javascript const sonic = new SonicBoom({ dest: '/var/log/app.log', minLength: 4096 }); sonic.write('Hello World'); ``` ``` -------------------------------- ### Log Rotation Friendly Configuration Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Uses periodic flushing and the reopen method to support production log rotation signals. ```javascript const sonic = new SonicBoom({ dest: './app.log', periodicFlush: 30000, // Flush every 30 seconds minLength: 4096, append: true }); // Handle log rotation signal process.on('SIGUSR2', () => { const timestamp = new Date().toISOString(); sonic.reopen(`./app.log.${timestamp}`); }); sonic.write('Application log\n'); ``` -------------------------------- ### Configure write modes Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Toggle between asynchronous non-blocking writes and synchronous blocking writes. ```javascript const sonic = new SonicBoom({ dest: './app.log', sync: false }); // Fast, non-blocking ``` ```javascript const sonic = new SonicBoom({ dest: './app.log', sync: true }); // Slow but immediate ``` -------------------------------- ### SonicBoom Default Behavior Error Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Attempting to initialize SonicBoom without providing either fd or dest will result in an error. ```javascript const sonic = new SonicBoom({}); // Error: Neither fd nor dest provided ``` -------------------------------- ### Default Configuration Options Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md The default settings used when initializing a new Sonic-boom instance. ```javascript { fd: undefined, // Must provide fd or dest dest: undefined, // Must provide fd or dest minLength: 0, // No minimum buffer size maxLength: 0, // No maximum buffer size maxWrite: 16384, // 16 KB per write periodicFlush: 0, // No periodic flushing sync: false, // Asynchronous writes fsync: false, // No fsync after writes append: true, // Append to file mode: undefined, // OS default (usually 0o644) mkdir: false, // Don't create directories contentMode: 'utf8', // Accept strings retryEAGAIN: () => true // Always retry EAGAIN/EBUSY } ``` -------------------------------- ### Critical Data Writing Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Use fsync to ensure data is physically written to disk and flushSync to force an immediate flush. ```javascript const sonic = new SonicBoom({ dest: './app.log', fsync: true }); sonic.write('critical\n'); sonic.flushSync(); ``` -------------------------------- ### Manage buffering and flushing Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Configure auto-flush thresholds or trigger manual flushes. ```javascript const sonic = new SonicBoom({ dest: './app.log', minLength: 4096 // Auto-flush at 4 KB }); // Manual flush with callback sonic.flush((err) => { if (!err) { console.log('Data flushed to disk'); } }); // Synchronous flush (blocks) sonic.flushSync(); ``` -------------------------------- ### Basic File Writing Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Uses default settings including asynchronous writes, UTF-8 encoding, and append mode. ```javascript const SonicBoom = require('sonic-boom'); const sonic = new SonicBoom({ dest: './app.log' }); sonic.write('log entry\n'); sonic.end(); ``` -------------------------------- ### constructor(opts: SonicBoomOpts) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Creates a new instance of the SonicBoom stream class. ```APIDOC ## constructor(opts: SonicBoomOpts) ### Description Initializes a new SonicBoom stream instance with the provided configuration options. ### Parameters - **opts** (SonicBoomOpts) - Required - Configuration options for the stream. ``` -------------------------------- ### Implement Log Rotation Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Uses the reopen method to rotate log files based on a daily schedule. ```javascript class RotatingLogger { constructor(basePath) { this.basePath = basePath; this.stream = new SonicBoom({ dest: basePath }); // Rotate daily this.scheduleRotation(); } scheduleRotation() { const now = new Date(); const tomorrow = new Date(now.getTime() + 86400000); tomorrow.setHours(0, 0, 0, 0); const delay = tomorrow - now; setTimeout(() => { const date = new Date().toISOString().split('T')[0]; this.stream.reopen(`${this.basePath}.${date}`); this.scheduleRotation(); }, delay); } log(message) { this.stream.write(message + '\n'); } close() { this.stream.end(); } } ``` -------------------------------- ### Check and Manage File Descriptor Limits Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Monitor system limits when handling high concurrency. Note that increasing limits on Linux typically requires the ulimit command. ```javascript // Check limits const os = require('os'); console.log('FD limit:', require('os').getSystemMemorySize()); // Increase limit (Linux) // ulimit -n 8192 ``` -------------------------------- ### reopen(file?) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Reopens the destination file, useful for log rotation. If already opening, defers the reopen until ready. If already ending, does nothing. ```APIDOC ## reopen(file?) ### Description Reopens the destination file, useful for log rotation. If already opening, defers the reopen until ready. If already ending, does nothing. ### Parameters - **file** (string | number) - Optional - New file path or descriptor. If omitted, reopens the original file. ### Returns - **void** ### Throws - **Error: "SonicBoom destroyed"** - Method called after destroy() - **Error: "Unable to reopen a file descriptor, you must pass a file to SonicBoom"** - Stream created with file descriptor (not path), and no file parameter provided ``` -------------------------------- ### SonicBoom#reopen([file]) Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Reopens the file in place, useful for log rotation. ```APIDOC ## SonicBoom#reopen([file]) ### Description Reopens the file in place, useful for log rotation. ``` -------------------------------- ### Configure Max Write Buffer Size Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Adjust the maxWrite option to optimize performance for non-Docker environments by increasing the buffer size. ```javascript const sonic = new SonicBoom({ dest: './app.log', maxWrite: 65536 // 64 KB }); ``` -------------------------------- ### Write to a file Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/00-START-HERE.txt Initializes a new SonicBoom instance and writes data to the specified destination. ```javascript new SonicBoom({ dest: './app.log' }).write(data) ``` -------------------------------- ### High-Performance Logging Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Optimized for throughput using larger batching windows, explicit buffer limits, and automatic directory creation. ```javascript const sonic = new SonicBoom({ dest: './app.log', minLength: 8192, // Batch writes maxLength: 1048576, // 1 MB max buffer maxWrite: 16384, // Standard chunk size append: true, mkdir: true }); // High throughput logging for (let i = 0; i < 100000; i++) { sonic.write(`log line ${i}\n`); } sonic.end(); ``` -------------------------------- ### SonicBoom#write(string) Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Writes the provided string to the file. ```APIDOC ## SonicBoom#write(string) ### Description Writes the string to the file. Returns false to signal the producer to slow down. ``` -------------------------------- ### flush(cb?) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Flushes buffered data to disk asynchronously. ```APIDOC ## flush(cb?) ### Description Flushes buffered data to disk if not currently writing. The callback is called when the flush operation completes. If `minLength` is `0`, this operation is a no-op. ### Parameters - **cb** (function) - Optional - Optional callback invoked on completion or error. ### Returns - **Void** ### Throws - **Error: "SonicBoom destroyed"** - Method called after `destroy()` and callback provided - **Error: "flush cb must be a function"** - Callback provided but not a function ``` -------------------------------- ### Network Stream via File Descriptor Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Demonstrates passing a network socket file descriptor to Sonic Boom. ```javascript const net = require('net'); const socket = net.createConnection({ host: 'logserver.local', port: 5000 }); socket.on('connect', () => { const sonic = new SonicBoom({ fd: socket.fd }); sonic.write('log\n'); }); ``` -------------------------------- ### SonicBoom#flushSync() Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Flushes the buffered data synchronously. ```APIDOC ## SonicBoom#flushSync() ### Description Flushes the buffered data synchronously. Note that this is a costly operation. ``` -------------------------------- ### Handle Backpressure Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Check the return value of write() to manage flow control and listen for the drain event to resume production. ```javascript if (!sonic.write(data)) { // Backpressure: pause producer } sonic.on('drain', () => { // Buffer drained: resume producer }); ``` -------------------------------- ### Rotate logs Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Use reopen() to switch the file destination without closing the stream instance. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); // Handle rotation signal process.on('SIGUSR2', () => { sonic.reopen('./app.log.1'); console.log('Rotated to new file'); }); sonic.write('log\n'); ``` -------------------------------- ### File Descriptor from Existing Open File Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Uses an existing file descriptor for cases requiring explicit control over file opening. ```javascript const fs = require('fs'); const fd = fs.openSync('./app.log', 'a'); const sonic = new SonicBoom({ fd }); sonic.write('data\n'); sonic.on('close', () => { // fd is now closed by sonic }); sonic.end(); ``` -------------------------------- ### Implement Synchronized Writes Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Configures the stream for synchronous operations to ensure data is persisted to disk immediately. ```javascript const sonic = new SonicBoom({ dest: './critical.log', sync: true, // Synchronous writes fsync: true // Force fsync }); // Each write blocks until persisted to disk sonic.write('Critical event\n'); sonic.flushSync(); console.log('Data on disk'); ``` -------------------------------- ### reopen(file?: string | number) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Reopens the file descriptor. ```APIDOC ## reopen ### Description Reopens the file descriptor, optionally with a new file path or descriptor. ### Signature `reopen(file?: string | number)` ``` -------------------------------- ### Handle finish event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered after end() is called and all buffered data is successfully written to disk. ```javascript sonic.on('finish', () => { console.log('All data written'); }); ``` -------------------------------- ### ContentMode Constants Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Defines the string literal types for the contentMode configuration option. ```APIDOC ## ContentMode Constants ### Description String literal types for the `contentMode` option, determining how data is handled by the stream. ### Type `type ContentMode = 'utf8' | 'buffer'` ### Values - **'utf8'** - Write string data. The stream converts strings to UTF-8 encoded buffers internally. - **'buffer'** - Write Buffer objects. Data is written as-is without encoding conversion. ### Example ```javascript // UTF-8 string mode (default) const sonic1 = new SonicBoom({ dest: './log.txt', contentMode: 'utf8' }); sonic1.write('Hello\n'); // Buffer mode const sonic2 = new SonicBoom({ dest: './data.bin', contentMode: 'buffer' }); sonic2.write(Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f])); ``` ``` -------------------------------- ### Binary Data Buffer Mode Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Configures the instance for binary or non-text data with larger buffer limits. ```javascript const sonic = new SonicBoom({ dest: './data.bin', contentMode: 'buffer', minLength: 4096, maxLength: 16777216 // 16 MB }); const buf = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]); // "Hello" sonic.write(buf); sonic.end(); ``` -------------------------------- ### Implement Batched Writes Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Buffers items in a queue and flushes them based on a timer or size constraints. ```javascript class BatchWriter { constructor(dest) { this.stream = new SonicBoom({ dest, minLength: 8192, // Batch until 8 KB maxLength: 1048576 // Max 1 MB in memory }); this.queue = []; this.timer = null; } write(item) { this.queue.push(item); if (!this.timer) { // Flush after 1 second or when batch size reached this.timer = setTimeout(() => this.flush(), 1000); } } flush() { if (this.timer) { clearTimeout(this.timer); this.timer = null; } for (const item of this.queue) { this.stream.write(JSON.stringify(item) + '\n'); } this.queue = []; } end() { this.flush(); this.stream.end(); } } ``` -------------------------------- ### flush(cb?: callback) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Flushes the internal buffer to the file. ```APIDOC ## flush(cb?: callback) ### Description Flushes the current buffer contents to the file system. ### Parameters - **cb** (callback) - Optional - Callback function executed after the flush operation completes. ``` -------------------------------- ### Synchronous Console-like Behavior Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Matches console.log behavior by flushing every write immediately, which is slower but ensures visibility. ```javascript const sonic = new SonicBoom({ dest: './debug.log', sync: true, minLength: 0 // Flush every write }); sonic.write('Debug: ' + value + '\n'); ``` -------------------------------- ### Constructor Validation Logic Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Internal checks performed during instantiation to ensure valid file descriptors, buffer sizes, and content modes. ```javascript // Must have fd or dest if (!fd && !dest) { throw new Error('SonicBoom supports only file descriptors and files'); } // minLength must be less than maxWrite if (minLength >= maxWrite) { throw new Error(`minLength should be smaller than maxWrite (${maxWrite})`); } // contentMode must be valid if (contentMode !== undefined && contentMode !== 'utf8' && contentMode !== 'buffer') { throw new Error(`SonicBoom supports "utf8" and "buffer", but passed ${contentMode}`); } // flush() callback must be a function if (cb != null && typeof cb !== 'function') { throw new Error('flush cb must be a function'); } ``` -------------------------------- ### write(data: string | Buffer) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Writes data to the file stream. ```APIDOC ## write ### Description Writes a string or buffer to the destination. ### Signature `write(data: string | Buffer)` ### Returns - **boolean** - Returns true if the data was written successfully, false otherwise. ``` -------------------------------- ### Custom Retry Strategy Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Implements backpressure handling by defining a custom retry strategy for EAGAIN errors. ```javascript const sonic = new SonicBoom({ dest: './app.log', retryEAGAIN: (err, writeBufferLen, remainingBufferLen) => { console.warn(`EAGAIN: ${writeBufferLen} bytes failed, ${remainingBufferLen} queued`); // Retry only if queue is small if (remainingBufferLen < 65536) { return true; // Retry } return false; // Stop and emit error } }); sonic.on('error', (err) => { if (err.code === 'EAGAIN') { console.error('Write queue too full, data lost'); } }); sonic.write('data\n'); ``` -------------------------------- ### SonicBoom#flush([cb]) Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Writes the current buffer to the file if a write is not in progress. ```APIDOC ## SonicBoom#flush([cb]) ### Description Writes the current buffer to the file. The optional callback is executed when the flush operation completes. ``` -------------------------------- ### Catching File System Errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/errors.md Listen for the 'error' event on the SonicBoom instance to handle asynchronous file system issues like permission errors or missing paths. ```javascript const sonic = new SonicBoom({ dest: './readonly/app.log' }); sonic.on('error', (err) => { if (err.code === 'EACCES') { console.log('Permission denied:', err.message); } else if (err.code === 'ENOENT') { console.log('Path not found:', err.message); } else { console.error('File system error:', err); } }); sonic.write('data\n'); ``` -------------------------------- ### Handle errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Distinguish between event-based file system errors and thrown logic errors. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); sonic.on('error', (err) => { // File system errors (permission, not found, etc) console.error('Stream error:', err.code, err.message); }); try { sonic.write('data'); sonic.write('data'); // OK sonic.destroy(); sonic.write('data'); // Throws: SonicBoom destroyed } catch (err) { console.error('Logic error:', err.message); } ``` -------------------------------- ### flushSync() Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Synchronously flushes the internal buffer to the destination. ```APIDOC ## flushSync ### Description Synchronously flushes the buffer to the file. ### Signature `flushSync()` ``` -------------------------------- ### SonicBoom Event Interface Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Overview of the events emitted by the SonicBoom instance, which inherits from EventEmitter. ```APIDOC ## SonicBoom Events ### Description SonicBoom instances emit various events to signal the state of the file stream and data processing operations. ### Events - **ready**: Emitted when the stream is ready to accept writes. - **drain**: Emitted when the internal buffer has been flushed and can accept more writes. - **write**: Emitted when data is successfully written to the underlying file. Returns the number of bytes written. - **drop**: Emitted when data is dropped due to exceeding `maxLength`. Returns the dropped data. - **error**: Emitted when an error occurs during file operations. Returns the error object. - **finish**: Emitted after `end()` is called and all buffered data has been written. - **close**: Emitted when the underlying file descriptor is closed. ``` -------------------------------- ### Critical Data Persistence Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Ensures data reaches persistent storage by enabling fsync and restricting file permissions. ```javascript const sonic = new SonicBoom({ dest: './critical.log', fsync: true, // Force OS write append: true, mode: 0o600 // Owner read/write only }); sonic.write('Critical transaction\n'); sonic.flushSync(); // Block until disk console.log('Data guaranteed on disk'); ``` -------------------------------- ### Flush buffered data synchronously Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Blocks the event loop to force an immediate write and sync of all buffered data to disk. ```javascript const sonic = new SonicBoom({ dest: './critical.log' }); sonic.write('critical message\n'); // Force immediate sync to disk try { sonic.flushSync(); console.log('Data definitely on disk'); } catch (err) { console.error('Sync flush failed:', err); } ``` -------------------------------- ### Flush buffered data asynchronously Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Flushes buffered data to disk. If minLength is 0, this operation is a no-op. ```javascript const sonic = new SonicBoom({ dest: './app.log', minLength: 4096 }); sonic.write('buffered data\n'); // Flush with callback sonic.flush((err) => { if (err) { console.error('Flush failed:', err); } else { console.log('Data flushed to disk'); } }); // Flush without callback sonic.flush(); ``` -------------------------------- ### Handle write event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered upon successful data write, providing the byte count as an argument. ```javascript sonic.on('write', (bytesWritten) => { console.log(`Wrote ${bytesWritten} bytes`); }); ``` -------------------------------- ### Reopen a log file Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Use the reopen method to rotate log files in place, typically triggered by a signal like SIGUSR2. ```js const stream = new SonicBoom({ dest: './my.log' }) process.on('SIGUSR2', function () { stream.reopen() }) ``` -------------------------------- ### flush(cb?: callback) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Flushes the internal buffer to the destination. ```APIDOC ## flush ### Description Flushes the current buffer to the file. ### Signature `flush(cb?: callback)` ### Parameters - **cb** (callback) - Optional - Callback function executed after flushing. ``` -------------------------------- ### Handle drop event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered when data is dropped due to exceeding the maxLength buffer limit. ```javascript sonic.on('drop', (data) => { console.log('Data dropped:', data); }); ``` -------------------------------- ### Synchronous Writing Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Enable sync mode for blocking writes, similar to console.log behavior. ```javascript const sonic = new SonicBoom({ dest: './app.log', sync: true }); sonic.write('immediate\n'); ``` -------------------------------- ### Log Rotation Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Reopen the file descriptor to a new path, typically triggered by a signal like SIGUSR2. ```javascript process.on('SIGUSR2', () => { sonic.reopen('./app.log.1'); }); ``` -------------------------------- ### Implement Logger with Backpressure Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Uses the 'drain' event to manage stream state and prevent memory overflow when writing logs. ```javascript class Logger { constructor(dest) { this.stream = new SonicBoom({ dest, minLength: 4096 }); this.paused = false; this.stream.on('drain', () => { this.paused = false; }); this.stream.on('error', (err) => { console.error('Log error:', err); }); } log(level, message) { const line = `[${level}] ${message}\n`; if (!this.paused) { if (!this.stream.write(line)) { this.paused = true; } } } close() { this.stream.end(); } } ``` -------------------------------- ### Rotate logs Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/00-START-HERE.txt Reopens the log file to a new destination path. ```javascript sonic.reopen('./app.log.1') ``` -------------------------------- ### end() Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Closes the stream gracefully. All buffered data is flushed before closing. Emits 'finish' event when all data is written, then 'close' event. ```APIDOC ## end() ### Description Closes the stream gracefully. All buffered data is flushed before closing. Emits 'finish' event when all data is written, then 'close' event. ### Returns - **void** ### Throws - **Error: "SonicBoom destroyed"** - Method called after destroy() ``` -------------------------------- ### Set Windows Terminal UTF-8 Encoding Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Run this command in cmd.exe or PowerShell to ensure correct UTF-8 character display. ```cmd chcp 65001 ``` -------------------------------- ### Handling reopen file descriptor errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/errors.md When using a file descriptor, you must provide a file path to the reopen method to successfully rotate or reopen the stream. ```javascript const fd = require('fs').openSync('./log.txt', 'a'); const sonic = new SonicBoom({ fd }); try { sonic.reopen(); // Error: need to provide new file } catch (err) { if (err.message.includes('Unable to reopen a file descriptor')) { console.log('Must provide new file path to reopen'); } } // Correct usage: sonic.reopen('./log.txt.1'); // OK with file path ``` -------------------------------- ### RetryEAGAIN Callback Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Defines the signature for the retryEAGAIN callback function used to handle EAGAIN or EBUSY errors during write operations. ```APIDOC ## RetryEAGAIN Callback ### Description Signature of the `retryEAGAIN` callback function used to determine if a write operation should be retried after an EAGAIN or EBUSY error. ### Signature `type RetryEAGAIN = (err: Error, writeBufferLen: number, remainingBufferLen: number) => boolean` ### Parameters - **err** (Error) - The EAGAIN or EBUSY error encountered. - **writeBufferLen** (number) - Byte length of the data attempted to write. - **remainingBufferLen** (number) - Byte length of data remaining in the buffer. ### Returns - **boolean** - `true` to retry the write operation, `false` to emit an 'error' event. ### Example ```javascript const sonic = new SonicBoom({ dest: './app.log', retryEAGAIN: (err, writeBufferLen, remainingBufferLen) => { console.log(`EAGAIN: ${writeBufferLen} bytes failed, ${remainingBufferLen} remaining`); return true; // Always retry } }); ``` ``` -------------------------------- ### SonicBoom#destroy() Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Closes the stream immediately without flushing. ```APIDOC ## SonicBoom#destroy() ### Description Closes the stream immediately; data is not flushed. ``` -------------------------------- ### Handle close event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered when the underlying file descriptor is closed following end(), destroy(), or a fatal error. ```javascript sonic.on('close', () => { console.log('File closed'); }); ``` -------------------------------- ### Writing to stdout/stderr Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/configuration.md Writes to standard streams via file descriptor; note that end/destroy should not be called on these. ```javascript const sonic = new SonicBoom({ fd: process.stdout.fd // Or process.stderr.fd }); sonic.write('Output\n'); // Note: Don't call end/destroy, as it would close stdout ``` -------------------------------- ### SonicBoom Parameter Precedence Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md When both fd and dest are provided, the dest parameter takes precedence and overwrites the fd value. ```javascript const sonic = new SonicBoom({ fd: 1, dest: './log.txt' }); // Uses './log.txt', not fd 1 ``` -------------------------------- ### destroy() Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Closes the stream immediately without flushing buffered data. Any data still in the buffer is lost. ```APIDOC ## destroy() ### Description Closes the stream immediately without flushing buffered data. Any data still in the buffer is lost. ### Returns - **void** ``` -------------------------------- ### Handling flush callback errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/errors.md Ensure the callback passed to the flush method is a function, null, or undefined to avoid this error. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); try { sonic.flush('invalid'); // Not a function } catch (err) { if (err.message === 'flush cb must be a function') { console.log('Callback must be a function'); } } // Correct usage: sonic.flush((err) => { console.log('Flush complete'); }); ``` -------------------------------- ### Define ContentMode types Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Defines the string literal types for the contentMode option, specifying whether to handle data as UTF-8 strings or raw buffers. ```typescript type ContentMode = 'utf8' | 'buffer' ``` -------------------------------- ### Handle error event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered during file operation failures or stream method errors. ```javascript sonic.on('error', (err) => { console.error('Stream error:', err); }); ``` -------------------------------- ### write(data) Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Writes data to the stream. Returns a boolean indicating if the producer should slow down due to backpressure. ```APIDOC ## write(data) ### Description Writes data to the stream. The stream will return false when backpressure is applied (internal buffer high-water mark exceeded), signaling the producer to slow down. ### Parameters - **data** (string | Buffer) - Required - Data to write. Type must match `contentMode` setting. ### Returns - **Boolean** - `true` if writing can continue, `false` if producer should slow down. ### Throws - **Error: "SonicBoom destroyed"** - Method called after `destroy()` ``` -------------------------------- ### end() Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Closes the stream gracefully. ```APIDOC ## end ### Description Ends the stream. ### Signature `end()` ``` -------------------------------- ### Define SonicBoomOpts interface Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md TypeScript definition for the configuration object used to initialize a SonicBoom instance. ```typescript type SonicBoomOpts = { fd?: number | string | symbol dest?: string | number maxLength?: number minLength?: number maxWrite?: number periodicFlush?: number sync?: boolean fsync?: boolean append?: boolean mode?: string | number mkdir?: boolean contentMode?: 'buffer' | 'utf8' retryEAGAIN?: (err: Error, writeBufferLen: number, remainingBufferLen: number) => boolean } ``` -------------------------------- ### Define RetryEAGAIN callback Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/types.md Defines the signature for the retryEAGAIN callback used to handle EAGAIN or EBUSY errors during write operations. ```typescript type RetryEAGAIN = ( err: Error, writeBufferLen: number, remainingBufferLen: number ) => boolean ``` -------------------------------- ### Write data to SonicBoom stream Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Writes data to the stream and handles backpressure signals. Returns false when the internal buffer high-water mark is exceeded. ```javascript const sonic = new SonicBoom({ dest: './output.log' }); // Simple write sonic.write('log message\n'); // Handle backpressure if (!sonic.write('more data\n')) { console.log('Producer should slow down'); } // Listen for drain event to resume sonic.on('drain', () => { console.log('Can resume writing'); }); ``` -------------------------------- ### Handle drain event Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Triggered when the internal buffer is flushed, allowing for producer backpressure management. ```javascript sonic.on('drain', () => { producer.resume(); // Resume writing from paused producer }); ``` -------------------------------- ### end() Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/README.md Signals the end of the stream. ```APIDOC ## end() ### Description Signals that no more data will be written to the stream. ``` -------------------------------- ### SonicBoom#end() Source: https://github.com/pinojs/sonic-boom/blob/master/README.md Closes the stream after flushing remaining data. ```APIDOC ## SonicBoom#end() ### Description Closes the stream, ensuring all data is flushed asynchronously. ``` -------------------------------- ### Catching SonicBoom destroyed errors Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/errors.md Demonstrates handling the error thrown when attempting operations on a destroyed stream, including both synchronous and asynchronous patterns. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); sonic.destroy(); try { sonic.write('data\n'); } catch (err) { if (err.message === 'SonicBoom destroyed') { console.log('Stream has been destroyed'); } } // For async flush() sonic.flush((err) => { if (err && err.message === 'SonicBoom destroyed') { console.log('Stream was destroyed before flush completed'); } }); ``` -------------------------------- ### Graceful Stream Termination Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Flushes all buffered data before closing the stream. Emits 'finish' and 'close' events upon completion. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); sonic.write('final message\n'); // Close gracefully sonic.end(); sonic.on('finish', () => { console.log('All data written'); }); sonic.on('close', () => { console.log('Stream closed'); }); ``` -------------------------------- ### Immediate Stream Destruction Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/api-reference/SonicBoom.md Closes the stream immediately without flushing the buffer. Any pending data will be lost. ```javascript const sonic = new SonicBoom({ dest: './app.log' }); sonic.write('data\n'); // Force close without flushing sonic.destroy(); sonic.on('close', () => { console.log('Stream closed'); }); ``` -------------------------------- ### destroy() Source: https://github.com/pinojs/sonic-boom/blob/master/_autodocs/INDEX.md Destroys the stream instance. ```APIDOC ## destroy ### Description Destroys the SonicBoom instance. ### Signature `destroy()` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.