### Usage of readFileP for file reading Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Example demonstrating how to read file contents into a buffer. ```javascript const { readFileP } = require('./lib/utils') readFileP('/tmp/screenshot.jpg') .then((buffer) => { console.log('Read', buffer.length, 'bytes') }) .catch((err) => { console.error('Failed to read file:', err) }) ``` -------------------------------- ### Usage of readAndUnlinkP for atomic cleanup Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Example demonstrating reading a temporary file and deleting it immediately after. ```javascript const { readAndUnlinkP } = require('./lib/utils') // Read screenshot from temp file and clean up readAndUnlinkP('/tmp/tmp-12345-screenshot.jpg') .then((imgBuffer) => { console.log('Screenshot read and temp file cleaned up') return imgBuffer }) .catch((err) => { console.error('Failed to read or delete temp file:', err) }) ``` -------------------------------- ### Install screenshot-desktop Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Install the package using npm. This command adds the screenshot-desktop package as a dependency to your project. ```bash $ npm install --save screenshot-desktop ``` -------------------------------- ### xrandr Output Example Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Sample output format from the xrandr command used for parsing display information. ```text HDMI-1 connected primary 1920x1080+0+0 (normal...) eDP-1 connected 2560x1440+1920+0 (normal...) DP-1 disconnected (normal...) ``` -------------------------------- ### Example output format for display list Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Sample raw output format returned by the batch script when listing displays. ```text \\.\\DISPLAY1;0;1920;1080;0 \\.\\DISPLAY2;0;3840;1080;1920 ``` -------------------------------- ### Usage of unlinkP for file deletion Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Example demonstrating how to delete a file and handle potential errors. ```javascript const { unlinkP } = require('./lib/utils') unlinkP('/tmp/screenshot.jpg') .then(() => { console.log('File deleted') }) .catch((err) => { console.error('Failed to delete file:', err) }) ``` -------------------------------- ### Platform-Specific Utility Imports Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Examples of how different platform modules import required utilities from the central utils file. ```javascript // macOS (lib/darwin/index.js) const { unlinkP, readAndUnlinkP } = require('../utils') // Linux (lib/linux/index.js) const { defaultAll } = require('../utils') // Windows (lib/win32/index.js) const { readAndUnlinkP, defaultAll } = require('../utils') ``` -------------------------------- ### Attaching Static Methods to Platform Modules Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Example of attaching static methods and constants to a platform-specific snapshot module before export. ```javascript darwinSnapshot.listDisplays = listDisplays darwinSnapshot.all = all darwinSnapshot.parseDisplaysOutput = parseDisplaysOutput darwinSnapshot.EXAMPLE_DISPLAYS_OUTPUT = EXAMPLE_DISPLAYS_OUTPUT module.exports = darwinSnapshot ``` -------------------------------- ### Handle Missing ImageMagick on Linux Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Detects if the 'import' command is missing on Linux, which indicates ImageMagick is not installed. ```javascript // Error: spawn import ENOENT screenshot() .catch((err) => { if (err.message.includes('ENOENT') && err.message.includes('import')) { console.error('ImageMagick not installed. Run: apt-get install imagemagick') } }) ``` -------------------------------- ### Locate Display Data in Output Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Use a regular expression to identify the start of the display data within the raw command output. ```javascript const displaysStartPattern = /2>nul {2}\|\| / const { 0: match, index } = displaysStartPattern.exec(output) ``` -------------------------------- ### Get display properties Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/listDisplays.md Accesses specific display properties, such as DPI scaling, which is particularly relevant for Windows environments. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { // Windows: get DPI-aware dimensions const firstDisplay = displays[0] if (firstDisplay.dpiScale) { console.log(`Display scaling: ${firstDisplay.dpiScale}x`) console.log(`Logical resolution: ${firstDisplay.width}x${firstDisplay.height}`) } }) ``` -------------------------------- ### Direct Usage of defaultAll Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Demonstrates how to invoke the defaultAll utility directly to capture all displays. ```javascript const defaultAll = require('./lib/utils').defaultAll const linuxSnapshot = require('./lib/linux') // Capture all displays using the generic implementation defaultAll(linuxSnapshot) .then((images) => { console.log('Captured', images.length, 'displays') images.forEach((img, idx) => { console.log(`Display ${idx}: ${img.length} bytes`) }) }) .catch((err) => { console.error('Failed to capture all displays:', err) }) ``` -------------------------------- ### Internal Platform Implementation Usage Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Shows how platform-specific snapshot modules integrate the defaultAll utility. ```javascript // In lib/linux/index.js linuxSnapshot.all = () => defaultAll(linuxSnapshot) // In lib/win32/index.js windowsSnapshot.all = () => defaultAll(windowsSnapshot) ``` -------------------------------- ### defaultAll(snapshot) Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Captures all connected displays by taking individual screenshots for each display and returning them as an array of Buffers. ```APIDOC ## defaultAll(snapshot) ### Description Generic implementation of bulk screenshot capture used by Linux and Windows implementations. Captures all connected displays by taking individual screenshots for each display and returning them as an array. ### Signature `function defaultAll(snapshot: Function): Promise` ### Parameters - **snapshot** (Function) - Required - Screenshot function with a `listDisplays()` method. Should be the platform-specific snapshot function. ### Returns - **Promise** - Array of image Buffers, one per display, in the order returned by `listDisplays()`. ### Errors - **Error** - Thrown if `snapshot.listDisplays()` fails to enumerate displays. - **Error** - Thrown if any individual `snapshot({ screen: id })` call fails. ### Example ```javascript const defaultAll = require('./lib/utils').defaultAll const linuxSnapshot = require('./lib/linux') defaultAll(linuxSnapshot) .then((images) => { console.log('Captured', images.length, 'displays') }) .catch((err) => { console.error('Failed to capture all displays:', err) }) ``` ``` -------------------------------- ### Capture and List Displays with screenshot-desktop Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Demonstrates basic usage for capturing primary displays, listing all connected displays, and capturing all displays simultaneously. ```javascript const screenshot = require('screenshot-desktop') // Capture primary display screenshot() .then((imgBuffer) => { // imgBuffer contains the screenshot data }) // List all displays screenshot.listDisplays() .then((displays) => { // displays is an array of Display objects }) // Capture all displays screenshot.all() .then((imgBuffers) => { // imgBuffers is an array of image Buffers }) ``` -------------------------------- ### View Project File Structure Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/MANIFEST.md Displays the directory layout of the project documentation. ```text /workspace/home/output/ ├── README.md (Start here) ├── DOCUMENTATION_INDEX.md (Full index and navigation) ├── MANIFEST.md (This file) ├── types.md (Type definitions) ├── configuration.md (Configuration reference) ├── errors.md (Error handling) ├── examples.md (Usage examples) └── api-reference/ ├── screenshot.md (Main function) ├── listDisplays.md (Display list) ├── all.md (Bulk capture) ├── utilities.md (Utility functions) ├── platform-implementations.md (Platform details) └── display-enumeration.md (Display detection) ``` -------------------------------- ### Enumerate Displays via xrandr Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Execute the xrandr command to list all connected display outputs and their current configurations. ```bash xrandr --current ``` -------------------------------- ### screenshot.listDisplays() Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/listDisplays.md Lists all available displays connected to the system. Returns a Promise that resolves to an array of Display objects. ```APIDOC ## screenshot.listDisplays() ### Description Lists all available displays connected to the system. Returns a Promise that resolves to an array of Display objects. ### Signature `screenshot.listDisplays(): Promise` ### Return Type `Promise` - Array of display objects. ### Display Object Properties - **id** (number | string) - Unique identifier for the display. - **name** (string) - Human-readable name/identifier for the display. - **primary** (boolean) - Whether this is the primary/main display (macOS, Linux). - **width** (number) - Display width in pixels (Linux, Windows). - **height** (number) - Display height in pixels (Linux, Windows). - **offsetX** (number) - X offset of display in virtual screen space (Linux, Windows). - **offsetY** (number) - Y offset of display in virtual screen space (Linux, Windows). - **crop** (string) - Crop string in format "WIDTHxHEIGHT+X+Y" (Linux). - **top** (number) - Top edge Y coordinate (Windows). - **right** (number) - Right edge X coordinate (Windows). - **bottom** (number) - Bottom edge Y coordinate (Windows). - **left** (number) - Left edge X coordinate (Windows). - **dpiScale** (number) - DPI scaling factor (Windows). ### Errors - **Error**: Thrown if the underlying system command fails (xrandr on Linux, system_profiler on macOS, batch script on Windows). ``` -------------------------------- ### screenshot(options?) Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/DOCUMENTATION_INDEX.md Captures a screenshot of the desktop. Returns a Promise that resolves to a Buffer or string. ```APIDOC ## screenshot(options?) ### Description Captures a screenshot of the desktop. Returns a Promise that resolves to a Buffer or string. ### Parameters - **options** (ScreenshotOptions) - Optional - Configuration for the screenshot capture. ``` -------------------------------- ### Command format for listing displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md The command structure used to list available displays via the batch script. ```text "{tmpBat}" /list ``` -------------------------------- ### screenshot(options) Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Captures a screenshot of the desktop or a specific display and returns a Buffer or file path. ```APIDOC ## screenshot(options) ### Description Captures a screenshot of the desktop or a specific display. Returns a Promise that resolves to a Buffer (if no filename is provided) or a string (the file path if a filename is provided). ### Parameters - **options** (Object) - Optional - Configuration object for the screenshot capture. - **filename** (string) - Optional - Path to save the screenshot file. - **format** (string) - Optional - Image format, e.g., 'jpg' or 'png'. - **screen** (number|string) - Optional - The display ID to capture, obtained from listDisplays(). - **linuxLibrary** (string) - Optional - Specifies the library to use on Linux ('scrot' or 'imagemagick'). ### Response - **Promise** - Resolves with the image data as a Buffer or the file path as a string. ``` -------------------------------- ### Architecture Overview Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Visual representation of the project's directory structure and platform detection logic. ```text index.js (platform detection) ├── lib/darwin/index.js (macOS implementation) ├── lib/linux/index.js (Linux implementation) └── lib/win32/index.js (Windows implementation) ``` -------------------------------- ### Basic Screenshot Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Captures a screenshot of the default display and returns it as a JPG Buffer. ```APIDOC ## screenshot() ### Description Captures a screenshot of the default display and returns it as a Buffer. ### Method ``` screenshot() ``` ### Parameters None ### Response #### Success Response - **img** (Buffer) - Buffer filled with JPG image data. ### Response Example ```json { "example": "img: Buffer filled with jpg goodness" } ``` ``` -------------------------------- ### screenshot.all() Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/all.md Captures a screenshot from every connected display simultaneously and returns an array of JPG image buffers. ```APIDOC ## screenshot.all() ### Description Captures a screenshot from every connected display simultaneously. This method is more efficient than calling individual screenshot captures for each display. ### Signature `screenshot.all(): Promise` ### Return Type `Promise` - Array of Buffers, one for each connected display, in the same order as returned by `listDisplays()`. Each Buffer contains JPG image data. ### Throws/Rejects - **Error**: Thrown if no displays are detected or if the screenshot command fails. ### Example ```javascript const screenshot = require('screenshot-desktop') const fs = require('fs') screenshot.all() .then((images) => { images.forEach((img, index) => { fs.writeFileSync(`display_${index}.jpg`, img) }) }) .catch((err) => { console.error('Failed to capture all displays:', err) }) ``` ``` -------------------------------- ### Use scrot on Linux Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/screenshot.md Configures the library to use the scrot utility on Linux, noting that format and screen selection are unsupported in this mode. ```javascript const screenshot = require('screenshot-desktop') screenshot({ linuxLibrary: 'scrot' }) .then((img) => { console.log('Captured with scrot') }) ``` -------------------------------- ### screenshot.listDisplays() Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Lists all connected displays and their properties. ```APIDOC ## screenshot.listDisplays() ### Description List all connected displays and their properties. ### Returns - **Promise** - Array of display objects containing id, name, primary, and platform-specific properties ``` -------------------------------- ### Generic Bulk Capture Implementation Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Provides a fallback implementation for platforms lacking native bulk capture by iterating through displays and executing promises in parallel. ```javascript function defaultAll(snapshot) Returns: Promise ``` -------------------------------- ### Handle Errors Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Demonstrates error handling for unsupported formats or missing system dependencies. ```javascript screenshot() .catch((err) => { if (err.message.includes('Invalid format')) { console.error('Unsupported format') } else if (err.code === 'ENOENT') { console.error('Required tool not found') } }) ``` -------------------------------- ### Query macOS display information Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Executes the system_profiler command to retrieve GPU and monitor metadata. ```bash system_profiler SPDisplaysDataType ``` -------------------------------- ### Capture Image Output Modes Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Shows the difference between returning raw buffer data and saving directly to a file. ```javascript screenshot() .then((buffer) => { // buffer is a Node.js Buffer with image data }) ``` ```javascript screenshot({ filename: 'my-screenshot.png' }) .then((filePath) => { // filePath is the absolute path string }) ``` -------------------------------- ### Capture basic screenshot to Buffer Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/screenshot.md Captures the primary display and returns the image data as a Buffer. ```javascript const screenshot = require('screenshot-desktop') screenshot().then((img) => { // img is a Buffer containing JPG data console.log('Screenshot captured:', img.length, 'bytes') }).catch((err) => { console.error('Failed to capture screenshot:', err) }) ``` -------------------------------- ### screenshot(options?: ScreenshotOptions): Promise Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/README.md Captures a screenshot of the primary display or a specified monitor. Returns an image Buffer if no filename is provided, or the absolute path to the saved file if a filename is specified. ```APIDOC ## screenshot(options?: ScreenshotOptions) ### Description Captures a screenshot of the primary display or a specified monitor. Returns an image Buffer if no filename is provided, or the absolute path to the saved file if a filename is specified. ### Parameters - **options** (ScreenshotOptions) - Optional - Configuration object including screen ID, filename, and format. ``` -------------------------------- ### List Displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Retrieves a list of all available displays on the system. ```APIDOC ## screenshot.listDisplays() ### Description Retrieves a list of all available displays on the system. ### Method ``` screenshot.listDisplays() ``` ### Parameters None ### Response #### Success Response - **displays** (Array) - An array of display objects, each with `id` and `name` properties. ### Response Example ```json { "example": "displays: [{ id, name }, { id, name }]" } ``` ``` -------------------------------- ### Implement Async/Await Pattern Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Use modern async/await syntax for cleaner asynchronous code flow instead of promise chains. ```javascript const screenshot = require('screenshot-desktop') async function captureScreenshot() { try { const displays = await screenshot.listDisplays() console.log(`Found ${displays.length} displays`) const img = await screenshot({ format: 'png', screen: displays[0].id }) console.log('Captured:', img.length, 'bytes') return img } catch (err) { console.error('Failed:', err.message) throw err } } // Call async function captureScreenshot() .catch((err) => { console.error('Async error:', err.message) }) ``` -------------------------------- ### Define all function Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Function definition for capturing all displays using the default utility. ```javascript windowsSnapshot.all = () => defaultAll(windowsSnapshot) ``` -------------------------------- ### Configure Linux Screenshot Library Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Choose between ImageMagick and scrot libraries on Linux systems. ImageMagick supports format and screen selection, while scrot is a simpler alternative. ```javascript const screenshot = require('screenshot-desktop') // Use ImageMagick (default, supports format and screen selection) screenshot({ format: 'png', screen: 'HDMI-1' }) .then((img) => console.log('ImageMagick capture')) // Use scrot (simpler, ignores format and screen options) screenshot({ linuxLibrary: 'scrot' }) .then((img) => console.log('Scrot capture')) ``` -------------------------------- ### Targeting displays on Linux Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Uses connector name strings to identify displays. ```javascript screenshot({ screen: 'HDMI-1' }) screenshot({ screen: 'eDP-1' }) ``` -------------------------------- ### Screenshot All Displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Captures a screenshot of all available displays on the system. ```APIDOC ## screenshot.all() ### Description Captures a screenshot of all available displays on the system. ### Method ``` screenshot.all() ``` ### Parameters None ### Response #### Success Response - **imgs** (Array) - An array of Buffers, one for each screen. ### Response Example ```json { "example": "imgs: an array of Buffers, one for each screen" } ``` ``` -------------------------------- ### Handle System Command Errors Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Use this pattern to catch errors related to missing platform dependencies or failed command execution. ```javascript screenshot() .catch((err) => { if (err.code === 'ENOENT') { console.error('Required command not found. Check platform dependencies.') } else if (err.message) { console.error('Screenshot capture failed:', err.message) } }) ``` -------------------------------- ### Handle File System Errors Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Use this pattern to catch permission issues or disk space constraints when writing screenshot files. ```javascript screenshot({ filename: '/root/protected.jpg' }) .catch((err) => { if (err.code === 'EACCES') { console.error('Permission denied writing to file') } else if (err.code === 'ENOSPC') { console.error('Insufficient disk space') } }) ``` -------------------------------- ### listDisplays() Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Enumerates available displays and returns an array of display objects. ```APIDOC ## listDisplays() ### Description Retrieves a list of all connected displays with their respective properties. ### Response - **Array** - A list of display objects containing: - **id** (number|string) - Unique identifier for the display. - **name** (string) - Human-readable name of the display. - **primary** (boolean) - Indicates if this is the primary display. - **width** (number) - Pixel width. - **height** (number) - Pixel height. - **offsetX** (number) - X offset in virtual space. - **offsetY** (number) - Y offset in virtual space. - **dpiScale** (number) - DPI scaling factor (Windows). ``` -------------------------------- ### Execute Windows Display Enumeration Script Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Run the batch script with the /list flag to retrieve connected display information. ```bash cmd.exe /c "screenCapture_1.3.2.bat" /list ``` -------------------------------- ### List all displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/listDisplays.md Iterates through all detected displays and logs their ID, name, resolution, and primary status to the console. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { displays.forEach(display => { console.log(`Display ${display.id}: ${display.name}`) if (display.width) { console.log(` Resolution: ${display.width}x${display.height}`) } if (display.primary) { console.log(' (primary display)') } }) }) .catch((err) => { console.error('Failed to list displays:', err) }) ``` -------------------------------- ### Implementation logic for readAndUnlinkP Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Internal implementation showing how readFileP and unlinkP are chained. ```javascript readFileP(path) .then((img) => { return unlinkP(path) .then(() => resolve(img)) .catch((err) => reject(err)) }) .catch((err) => reject(err)) ``` -------------------------------- ### Perform Parallel Captures Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Use Promise.all to capture multiple displays concurrently for improved performance. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { // Capture all displays in parallel const capturePromises = displays.map((display) => { return screenshot({ screen: display.id }) .then((img) => ({ display: display.name, buffer: img, displayId: display.id })) }) return Promise.all(capturePromises) }) .then((results) => { console.log(`Captured all ${results.length} displays`) results.forEach(({ display, buffer }) => { console.log(` ${display}: ${buffer.length} bytes`) }) }) .catch((err) => { console.error('Failed:', err.message) }) ``` -------------------------------- ### List Available Displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Retrieves a list of all connected displays and their properties, including ID, name, and resolution. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { console.log(`Found ${displays.length} display(s):`) displays.forEach((display) => { console.log(` [${display.id}] ${display.name}`) if (display.primary) { console.log(' (primary display)') } // Platform-specific properties if (display.width && display.height) { console.log(` Resolution: ${display.width}x${display.height}`) } }) }) .catch((err) => { console.error('Failed to list displays:', err.message) }) ``` -------------------------------- ### readFileP(path) Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md A promisified wrapper around fs.readFile() for reading files into memory. ```APIDOC ## readFileP(path) ### Description Promisified wrapper around fs.readFile() for reading files into memory. ### Parameters - **path** (string) - Required - Absolute or relative file path to read ### Return Type Promise - Buffer containing the file contents ### Errors - **Error (ENOENT)**: File does not exist - **Error (EACCES)**: Permission denied to read file - **Error (EISDIR)**: Path is a directory, not a file ``` -------------------------------- ### Handle screenshot errors with fallbacks Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Demonstrates how to catch specific error types such as invalid formats, missing displays, and permission issues to provide actionable feedback. ```javascript const screenshot = require('screenshot-desktop') screenshot({ format: 'png', filename: 'output.png' }) .then((filePath) => { console.log('Success! Saved to:', filePath) }) .catch((err) => { // Check error type if (err.message.includes('Invalid format')) { console.error('ERROR: Unsupported format. Try png or jpg.') } else if (err.message.includes('Invalid choice of displayId')) { console.error('ERROR: Display not found.') // Show available displays return screenshot.listDisplays() .then((displays) => { console.log('Available displays:') displays.forEach(d => console.log(` [${d.id}] ${d.name}`)) }) } else if (err.code === 'EACCES') { console.error('ERROR: Permission denied writing to file.') } else if (err.code === 'ENOENT') { console.error('ERROR: Required command not found.') if (process.platform === 'linux') { console.error('Hint: apt-get install imagemagick') } } else { console.error('ERROR:', err.message) } }) ``` -------------------------------- ### Handle Missing xrandr on Linux Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Detects if xrandr is unavailable when attempting to enumerate displays on Linux. ```javascript // Error from xrandr execution screenshot.listDisplays() .catch((err) => { if (err.message.includes('xrandr')) { console.error('xrandr not available. Cannot enumerate displays.') } }) ``` -------------------------------- ### Detect Platform-Specific Issues Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Provides platform-specific guidance by checking the process.platform property within the catch block. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { if (displays.length === 0) { console.error('No displays detected') return } return screenshot() }) .catch((err) => { console.error('Screenshot error:', err.message) // Provide platform-specific guidance if (process.platform === 'linux') { console.error('Linux hint: Ensure ImageMagick is installed (apt-get install imagemagick)') } else if (process.platform === 'darwin') { console.error('macOS hint: Ensure screencapture utility is available') } else if (process.platform === 'win32') { console.error('Windows hint: Ensure batch script resources are accessible') } }) ``` -------------------------------- ### Implement Comprehensive Error Handling Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Demonstrates a robust pattern for catching and differentiating between various error types including validation, permission, and dependency issues. ```javascript const screenshot = require('screenshot-desktop') screenshot({ format: 'png', filename: 'output.png' }) .then((filePath) => { console.log('Screenshot saved to:', filePath) }) .catch((err) => { // Check for specific validation errors first if (err.message.includes('Invalid format')) { console.error('Unsupported image format') } else if (err.message.includes('Invalid choice of displayId')) { console.error('Display not found. Available displays:') return screenshot.listDisplays() .then((displays) => { displays.forEach(d => console.log(` - ${d.id}: ${d.name}`)) }) } else if (err.code === 'EACCES') { console.error('Permission denied. Check file path permissions.') } else if (err.code === 'ENOENT') { console.error('Required command not found. Check platform dependencies.') } else { console.error('Unknown error:', err.message || err) } }) ``` -------------------------------- ### Command format for batch script execution Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md The command structure used to execute the screenshot batch script. ```text cmd.exe /c {tmpBat} {imagePath} [/d {displayName}] ``` -------------------------------- ### Batch Capture with Sequential Naming Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Saves multiple screenshots to a directory with sequential filenames. Uses Promise.all to manage concurrent capture operations. ```javascript const screenshot = require('screenshot-desktop') const fs = require('fs') const path = require('path') function batchCapture(outputDir, count, displayId) { const promises = [] for (let i = 1; i <= count; i++) { const filename = path.join( outputDir, `screenshot_${String(i).padStart(3, '0')}.jpg` ) const promise = screenshot({ filename: filename, screen: displayId }) .then(() => { console.log(`✓ ${i}/${count}`) }) .catch((err) => { console.error(`✗ ${i}/${count}: ${err.message}`) }) promises.push(promise) } return Promise.all(promises) } // Capture 10 screenshots batchCapture('./screenshots', 10, 0) .then(() => { console.log('Batch capture complete') }) ``` -------------------------------- ### Specify Output Format Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Configures the image format for the captured screenshot, supporting platform-dependent formats like PNG or JPG. ```javascript const screenshot = require('screenshot-desktop') // Capture as PNG (lossless) screenshot({ format: 'png' }) .then((img) => { console.log('PNG screenshot captured:', img.length, 'bytes') }) // Capture as JPG (lossy, smaller file) screenshot({ format: 'jpg' }) .then((img) => { console.log('JPG screenshot captured:', img.length, 'bytes') }) // Both formats with file saving screenshot({ filename: 'shot.png', format: 'png' }) screenshot({ filename: 'shot.jpg', format: 'jpg' }) ``` -------------------------------- ### Capture all displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/all.md Captures screenshots from all connected displays and saves each as a separate JPG file. ```javascript const screenshot = require('screenshot-desktop') const fs = require('fs') screenshot.all() .then((images) => { console.log(`Captured ${images.length} display(s)`) images.forEach((img, index) => { fs.writeFileSync(`display_${index}.jpg`, img) console.log(`Saved display_${index}.jpg`) }) }) .catch((err) => { console.error('Failed to capture all displays:', err) }) ``` -------------------------------- ### Scrot Command Template Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md The command structure used by the scrot utility for capturing screenshots. ```bash scrot {filename} -e -z echo "{filename}" ``` -------------------------------- ### Capture Default Screenshot (JPG) Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Capture a screenshot and receive it as a JPG formatted buffer. This is the default behavior when no format is specified. ```javascript const screenshot = require('screenshot-desktop') screenshot().then((img) => { // img: Buffer filled with jpg goodness // ... }).catch((err) => { // ... }) ``` -------------------------------- ### Map display properties to objects Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Converts the parsed GPU display entries into a simplified array of display objects. ```javascript const temp = Object.entries(gpu.Displays) .map(([name, props]) => { const primary = props['Main Display'] === 'Yes' return { name, primary } }) ``` -------------------------------- ### Capture Screenshots of All Displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Capture screenshots of all available displays simultaneously. The result is an array of image buffers, one for each screen. ```javascript const screenshot = require('screenshot-desktop') screenshot.all().then((imgs) => { // imgs: an array of Buffers, one for each screen }) ``` -------------------------------- ### Handle Windows DPI Scaling Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Account for high-DPI displays on Windows by checking the dpiScale property of detected displays. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { displays.forEach((display) => { if (display.dpiScale && display.dpiScale > 1) { console.log(`${display.name}: ${display.width}x${display.height} @ ${display.dpiScale}x DPI`) console.log(` Physical pixels: ${display.width * display.dpiScale}x${display.height * display.dpiScale}`) } }) }) ``` -------------------------------- ### Define ScreenshotOptions interface Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/types.md Configuration object passed to the main screenshot() function to control output path, format, and target display. ```typescript interface ScreenshotOptions { filename?: string format?: string screen?: number | string linuxLibrary?: string } ``` -------------------------------- ### Screenshot with Format Option Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Captures a screenshot and allows specifying the output format (e.g., PNG). ```APIDOC ## screenshot(options) ### Description Captures a screenshot with a specified format. ### Method ``` screenshot({format: 'png'}) ``` ### Parameters #### Request Body - **format** (string) - Optional. Valid values `png|jpg`. Specifies the output image format. ### Response #### Success Response - **img** (Buffer) - Buffer filled with image data in the specified format. ### Response Example ```json { "example": "img: Buffer filled with png goodness" } ``` ``` -------------------------------- ### Process all screenshots Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/all.md Captures all displays and processes the resulting image buffers asynchronously. ```javascript const screenshot = require('screenshot-desktop') screenshot.all() .then((images) => { return Promise.all(images.map(async (img, idx) => { // Process each image (e.g., compress, analyze, etc.) console.log(`Image ${idx}: ${img.length} bytes`) return img })) }) ``` -------------------------------- ### Capture Screenshot of Specific Display Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md List available displays and capture a screenshot of the last display in the list. Requires prior execution of `listDisplays()`. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays().then((displays) => { // displays: [{ id, name }, { id, name }] screenshot({ screen: displays[displays.length - 1].id }) .then((img) => { // img: Buffer of screenshot of the last display }); }) ``` -------------------------------- ### Targeting displays on Windows Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Uses display name strings to identify displays. ```javascript screenshot({ screen: '\\.\\DISPLAY1' }) screenshot({ screen: '\\.\\DISPLAY2' }) ``` -------------------------------- ### Screenshot Options Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Details on the available options for the screenshot function. ```APIDOC ## screenshot() options ### Description Configuration options for the `screenshot()` function. ### Parameters #### Request Body - **filename** (string) - Optional. Absolute or relative path to save output. - **format** (string) - Optional. Valid values `png|jpg`. Specifies the output image format. - **linuxLibrary** (string) - Optional. Linux only. Valid values `scrot|imagemagick`. Which library to use. Note that scrot does not support format or screen selection. ``` -------------------------------- ### Handle Screenshot Errors Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Use this pattern to differentiate between validation errors and system-level issues like missing commands or permission denials. ```javascript screenshot() .catch((err) => { if (err.message.includes('Invalid')) { // Handle validation error } else if (err.code === 'ENOENT') { // Required command not found } else if (err.code === 'EACCES') { // Permission denied } else { // Other error } }) ``` -------------------------------- ### Display object structure Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Describes the properties returned for display devices, including identifiers, dimensions, and platform-specific metadata like DPI scaling. ```javascript { id: number|string // Unique identifier name: string // Human-readable name primary?: boolean // Is this the primary display? width?: number // Pixel width (Linux, Windows) height?: number // Pixel height (Linux, Windows) offsetX?: number // X offset in virtual space (Linux, Windows) offsetY?: number // Y offset in virtual space (Linux, Windows) dpiScale?: number // DPI scaling factor (Windows) // ... other platform-specific properties } ``` -------------------------------- ### Capture with specific format Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/screenshot.md Specifies the output image format, such as PNG. ```javascript const screenshot = require('screenshot-desktop') screenshot({ format: 'png' }) .then((img) => { // PNG format is lossless console.log('PNG screenshot captured') }) ``` -------------------------------- ### Error handling pattern Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Demonstrates the standard promise-based approach for handling successful captures and potential errors using .then() and .catch(). ```javascript screenshot(options) .then(result => { // Success: result is Buffer or string (file path) }) .catch(err => { // Check err.message or err.code for error type // See errors.md for complete error catalog }) ``` -------------------------------- ### Capture All Displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Captures screenshots from all connected monitors in a single operation. ```javascript const screenshot = require('screenshot-desktop') const fs = require('fs') screenshot.all() .then((images) => { console.log(`Captured ${images.length} display(s)`) images.forEach((img, index) => { const filename = `display_${index}.jpg` fs.writeFileSync(filename, img) console.log(`Saved ${filename} (${img.length} bytes)`) }) }) .catch((err) => { console.error('Failed to capture all displays:', err.message) }) ``` -------------------------------- ### Capture Screenshot as PNG Source: https://github.com/bencevans/screenshot-desktop/blob/main/README.md Capture a screenshot and specify the output format as PNG. The result is a buffer containing the PNG image data. ```javascript const screenshot = require('screenshot-desktop') screenshot({format: 'png'}).then((img) => { // img: Buffer filled with png goodness // ... }).catch((err) => { // ... }) ``` -------------------------------- ### Capture all displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/listDisplays.md Identifies the primary display from the list and captures a screenshot of it using the display's ID. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { console.log(`Found ${displays.length} display(s)`) // Capture primary display const primary = displays.find(d => d.primary) || displays[0] return screenshot({ screen: primary.id }) }) .then((img) => { console.log('Captured primary display') }) ``` -------------------------------- ### readAndUnlinkP(path) Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md Combines file reading and deletion: reads file contents then deletes the file. ```APIDOC ## readAndUnlinkP(path) ### Description Combines file reading and deletion: reads file contents then deletes the file. Used internally to read temporary screenshot files and clean them up atomically. ### Parameters - **path** (string) - Required - Absolute or relative file path to read and delete ### Return Type Promise - Buffer containing the file contents before deletion ### Errors - **Error (ENOENT)**: File does not exist - **Error (EACCES)**: Permission denied to read or delete file - **Error (EISDIR)**: Path is a directory ``` -------------------------------- ### Compare Multiple Displays Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Captures multiple specific displays concurrently for comparison or processing. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { console.log(`Capturing ${displays.length} displays...`) // Capture each display const promises = displays.map((display) => { return screenshot({ screen: display.id }) .then((img) => ({ display: display.name, image: img, size: img.length })) .catch((err) => ({ display: display.name, error: err.message })) }) return Promise.all(promises) }) .then((results) => { results.forEach((result) => { if (result.error) { console.log(`${result.display}: ERROR - ${result.error}`) } else { console.log(`${result.display}: ${result.size} bytes`) } }) }) ``` -------------------------------- ### macOS all Function Signature Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Signature for the all function used to capture all connected displays on macOS. ```javascript function all() Returns: Promise ``` -------------------------------- ### Promisified File Reading Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Promisified wrapper for fs.readFile for asynchronous file access. ```javascript function readFileP(path) Returns: Promise ``` -------------------------------- ### Capture specific display Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/screenshot.md Lists available displays and captures a specific screen by its ID. ```javascript const screenshot = require('screenshot-desktop') screenshot.listDisplays() .then((displays) => { console.log('Available displays:', displays) // Capture the second display return screenshot({ screen: displays[1].id }) }) .then((img) => { console.log('Captured second display:', img.length, 'bytes') }) .catch((err) => { console.error('Error:', err) }) ``` -------------------------------- ### Implement Timeout Handling Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Add a timeout to screenshot operations using Promise.race to prevent the process from hanging indefinitely. ```javascript const screenshot = require('screenshot-desktop') function captureWithTimeout(timeoutMs = 5000) { const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject(new Error(`Screenshot capture timed out after ${timeoutMs}ms`)) }, timeoutMs) }) return Promise.race([ screenshot(), timeoutPromise ]) } captureWithTimeout(5000) .then((img) => { console.log('Captured:', img.length, 'bytes') }) .catch((err) => { console.error('Error:', err.message) }) ``` -------------------------------- ### Linux Snapshot Function Signature Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md The primary function for capturing screenshots on Linux. ```javascript function linuxSnapshot(options = {}) Returns: Promise ``` -------------------------------- ### ImageMagick Command Template Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md The command structure used by ImageMagick's import utility for capturing screenshots. ```bash import -silent -window root -crop {crop} -screen {format}:{filename} ``` -------------------------------- ### Platform-Specific Module Export Pattern Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Determines the appropriate platform module to export based on the current process platform. ```javascript // index.js if (process.platform === 'linux') { module.exports = require('./lib/linux') } else if (process.platform === 'darwin') { module.exports = require('./lib/darwin') } else if (process.platform === 'win32') { module.exports = require('./lib/win32') } else { module.exports = function unSupported () { return Promise.reject(new Error('Currently unsupported platform. Pull requests welcome!')) } } ``` -------------------------------- ### Parse Display Data Format Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Use regex to capture display ID, coordinate bounds, and DPI scale from the formatted string. ```javascript /(.*?);(.?\d+);(.?\d+);(.?\d+);(.?\d+);(.?\d*[\.,]?\d+)/ ``` -------------------------------- ### Buffer Size Formula Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md The mathematical formula used to determine the maximum buffer size. ```javascript Math.max(total_pixels * 8, 10 * 1024 * 1024) ``` -------------------------------- ### defaultAll Function Signature Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/utilities.md The function signature for the defaultAll utility. ```javascript function defaultAll(snapshot: Function): Promise ``` -------------------------------- ### Fallback to buffer on file save failure Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/examples.md Implements a wrapper function that attempts to save a screenshot to a file and returns the image buffer if the file operation fails. ```javascript const screenshot = require('screenshot-desktop') const fs = require('fs') function captureScreenshot(filepath) { return screenshot({ filename: filepath }) .catch((err) => { console.warn(`Failed to save to ${filepath}, returning buffer instead`) console.warn(`Reason: ${err.message}`) return screenshot() // Fall back to buffer mode }) } captureScreenshot('/restricted/path/screenshot.png') .then((result) => { if (typeof result === 'string') { console.log('Saved to file:', result) } else { console.log('Got image buffer:', result.length, 'bytes') } }) .catch((err) => { console.error('Complete failure:', err.message) }) ``` -------------------------------- ### Calculate Display Dimensions Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Derive width and height from the parsed coordinate bounds. ```javascript width: d.right - d.left // 1920 - 0 = 1920 height: d.bottom - d.top // 1080 - 0 = 1080 ``` -------------------------------- ### Main screenshot function signature Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/START_HERE.md Defines the options available for the screenshot function, including file output, format, display selection, and Linux-specific library configuration. ```javascript screenshot(options?: { filename?: string // Save to file instead of Buffer format?: string // 'jpg' | 'png' | (platform-specific) screen?: number|string // Display ID (from listDisplays()) linuxLibrary?: string // 'scrot' | 'imagemagick' (Linux only) }): Promise ``` -------------------------------- ### Display Object Structure Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md The final structured object representing a single display configuration. ```javascript { id: 'HDMI-1', // Same as connector name name: 'HDMI-1', // Connector name primary: true, width: 1920, height: 1080, offsetX: 0, offsetY: 0, crop: '1920x1080+0+0' } ``` -------------------------------- ### Handle No Displays Detected Error Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/errors.md Catch errors when no displays are detected on macOS or Linux systems. ```javascript screenshot() .catch((err) => { if (err.message.includes('No displays detected')) { console.error('System has no connected displays') } }) ``` -------------------------------- ### Define Display interface Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/types.md Represents a connected display or monitor, providing metadata such as resolution, offsets, and unique identifiers. ```typescript interface Display { id: number | string name: string primary?: boolean width?: number height?: number offsetX?: number offsetY?: number crop?: string top?: number right?: number bottom?: number left?: number dpiScale?: number } ``` -------------------------------- ### Targeting displays on macOS Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/display-enumeration.md Uses 0-indexed numeric IDs to select displays. ```javascript screenshot({ screen: 0 }) // First display (usually primary) screenshot({ screen: 1 }) // Second display ``` -------------------------------- ### Define windowsSnapshot function Source: https://github.com/bencevans/screenshot-desktop/blob/main/_autodocs/api-reference/platform-implementations.md Core function signature for capturing screenshots on Windows. ```javascript function windowsSnapshot(options = {}) Returns: Promise ```