System Interaction
Working Directory
Section titled “Working Directory”Usage: cd(path: string | SAF): void
Changes the current working directory with support for tilde expansion.
Parameters:
path
- Target directory path (string) or SAF instance
Examples:
// Change to home directorycd("~")
// Change to project directorycd("~/projects/bunmagic")
// Change to relative directorycd("./dist")
Usage: cwd(): Promise<string>
Gets the current working directory path.
Returns:
- Promise resolving to the current working directory path
Examples:
// Get current directoryconst currentDir = await cwd()console.log(`Working in: ${currentDir}`)
// Use in conditional logicif ((await cwd()).includes("projects")) { console.log("Currently in projects folder")}
System Information
Section titled “System Information”Type: NodeJS.OS
Node.js operating system module, available as a global for OS-related utilities.
Examples:
// Get operating system platformconst platform = os.platform() // "darwin", "linux", "win32", etc.
// Get home directoryconst home = os.homedir() // "/Users/username" or "C:\Users\username"
// Get temporary directoryconst temp = os.tmpdir() // "/tmp" or "C:\Users\username\AppData\Local\Temp"
// Get system architectureconst arch = os.arch() // "x64", "arm64", etc.
// Get hostnameconst hostname = os.hostname() // "my-computer.local"
// Get OS release/versionconst release = os.release() // "22.1.0" on macOS
// Get CPU informationconst cpus = os.cpus() // Array of CPU core information
// Get memory informationconst totalMem = os.totalmem() // Total system memory in bytesconst freeMem = os.freemem() // Available memory in bytes
// Get network interfacesconst interfaces = os.networkInterfaces()
// Platform-specific logicif (os.platform() === "darwin") { console.log("Running on macOS")} else if (os.platform() === "win32") { console.log("Running on Windows")} else { console.log("Running on Linux/Unix")}
isMacOS()
Section titled “isMacOS()”Usage: isMacOS(): Promise<boolean>
Checks if the current platform is macOS.
Parameters:
- None
Returns:
- Promise resolving to
true
if running on macOS,false
otherwise
Behavior:
The function checks if process.platform
equals 'darwin'
, which is Node.js’s identifier for macOS.
Examples:
// Basic platform checkif (await isMacOS()) { console.log("Running on macOS")} else { console.log("Not running on macOS")}
// Conditional logic for platform-specific operationsasync function openFile(path: string) { if (await isMacOS()) { await $`open "${path}"` } else { console.log("File opening not implemented for this platform") }}
// Platform-specific configurationconst config = { editor: await isMacOS() ? "code" : "nano", browser: await isMacOS() ? "open" : "xdg-open"}
// Using with other platform utilitiesasync function setupEnvironment() { if (await isMacOS()) { console.log("Setting up macOS environment...") await $`brew install git` } else { console.log("Setting up non-macOS environment...") }}
Utilities
Section titled “Utilities”$stdin()
Section titled “$stdin()”Usage: $stdin(): Promise<string>
Reads all data from stdin as a string. Useful for piping data into Bunmagic scripts from the command line.
Parameters:
- None
Returns:
- Promise that resolves to the complete stdin content as a string
Behavior: The function asynchronously reads all data from stdin using Bun’s streaming API and concatenates it into a single string. It handles:
- Multiple chunks of data
- Large inputs through streaming
- Proper UTF-8 encoding
- Empty input (returns empty string)
Examples:
// Basic stdin readingconst input = await $stdin()console.log(`Received: ${input}`)
// Process piped JSON dataconst jsonData = await $stdin()const data = JSON.parse(jsonData)console.log(`Processing ${data.items.length} items`)
// Filter lines from stdinconst text = await $stdin()const filtered = text .split('\n') .filter(line => line.includes('ERROR')) .join('\n')console.log(filtered)
// Command line usage examples:// echo "Hello, World!" | bunmagic run my-script// cat data.txt | bunmagic run process-data// curl -s https://api.example.com/data | bunmagic run parse-api
// Process CSV data from stdinconst csvData = await $stdin()const lines = csvData.trim().split('\n')const headers = lines[0].split(',')const rows = lines.slice(1).map(line => { const values = line.split(',') return Object.fromEntries( headers.map((header, i) => [header, values[i]]) )})console.log(`Processed ${rows.length} rows`)
// Chain with other shell commandsconst result = await $stdin()const processed = result.toUpperCase()await $`echo ${processed} | sort | uniq`
sleep()
Section titled “sleep()”Usage: sleep(ms: number): Promise<void>
Pauses execution for a specified number of milliseconds.
Parameters:
ms
- The number of milliseconds to sleep
Returns:
- Promise that resolves after the specified delay
Examples:
// Basic delayawait sleep(1000) // Wait 1 secondconsole.log("This runs after 1 second")
// Short delay for rate limitingfor (const item of items) { await processItem(item) await sleep(100) // 100ms delay between items}
// Timeout simulationconsole.log("Starting process...")await sleep(2500) // Wait 2.5 secondsconsole.log("Process complete!")
// Using in error handling/retry logicasync function retryOperation() { for (let attempt = 1; attempt <= 3; attempt++) { try { return await riskyOperation() } catch (error) { if (attempt < 3) { console.log(`Attempt ${attempt} failed, retrying in 1 second...`) await sleep(1000) } else { throw error } } }}
slugify()
Section titled “slugify()”Usage: slugify(text: string): string
Converts text to a URL-friendly slug format.
Parameters:
text
- The input text to convert to a slug
Returns:
- String formatted as a URL-friendly slug
Behavior: The function performs the following transformations:
- Converts text to lowercase
- Replaces whitespace sequences with single hyphens
- Removes all non-word characters (except hyphens)
- Replaces multiple consecutive hyphens with single hyphens
- Trims whitespace from the result
- Removes leading and trailing hyphens
Examples:
// Basic text conversionconst slug1 = slugify("Hello World")console.log(slug1) // "hello-world"
// Text with special charactersconst slug2 = slugify("My Awesome Blog Post!")console.log(slug2) // "my-awesome-blog-post"
// Text with multiple spaces and symbolsconst slug3 = slugify(" Multiple Spaces & Special #Characters ")console.log(slug3) // "multiple-spaces-special-characters"
// Text with numbers and mixed caseconst slug4 = slugify("React 18: New Features")console.log(slug4) // "react-18-new-features"
// Edge casesconst slug5 = slugify("---Leading and Trailing Hyphens---")console.log(slug5) // "leading-and-trailing-hyphens"
const slug6 = slugify("CamelCase and snake_case")console.log(slug6) // "camelcase-and-snakecase"
Clipboard Operations
Section titled “Clipboard Operations”copyToClipboard()
Section titled “copyToClipboard()”Usage: copyToClipboard(text: string): Promise<void>
Copies text to the system clipboard.
Parameters:
text
- String to copy to clipboard
Examples:
// Basic usageawait copyToClipboard("Text to copy")console.log("Copied to clipboard!")
// Copy command outputconst output = await $`git remote -v`.text()await copyToClipboard(output)console.log("Remote info copied to clipboard")
// Copy generated contentconst token = generateToken()await copyToClipboard(token)console.log(ansis.green("API token generated and copied to clipboard"))