{"id":13637,"library":"node-osascript","title":"AppleScript Execution from Node.js","description":"node-osascript is a utility library for Node.js that enables the execution of AppleScript code directly from JavaScript. It facilitates bidirectional communication by allowing JavaScript variables to be injected into AppleScript and by transforming AppleScript results (lists, records, dates, numbers, booleans, strings) into their corresponding JavaScript data types using PEG.js. The current stable version is 2.1.0, last published over 8 years ago. While the release cadence is not explicitly stated, the project appears to be in a maintenance or abandoned phase given its age. Its key differentiator is the automatic, structured type conversion of AppleScript results into native JavaScript objects, simplifying data handling compared to raw `exec` calls, which typically return plain strings.","status":"maintenance","version":"2.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/FWeinb/node-osascript","tags":["javascript","apple","script","applescript","osascript"],"install":[{"cmd":"npm install node-osascript","lang":"bash","label":"npm"},{"cmd":"yarn add node-osascript","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-osascript","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package primarily exports a default object via CommonJS. For ESM contexts, a default import is typically used, or direct `require` with `createRequire` if needed for older Node.js versions or complex CJS/ESM interop.","wrong":"const { execute } = require('node-osascript');","symbol":"osascript","correct":"import osascript from 'node-osascript';"},{"note":"The `execute` function is a method on the default exported `osascript` object, not a named export. Attempting to destructure it as a named export will result in a TypeError.","wrong":"import { execute } from 'node-osascript';","symbol":"execute","correct":"const osascript = require('node-osascript');\nosascript.execute('...', (err, result) => { /* ... */ });"},{"note":"Similar to `execute`, `executeFile` is a method on the default `osascript` object. It's used for running external AppleScript files.","wrong":"import { executeFile } from 'node-osascript';","symbol":"executeFile","correct":"const osascript = require('node-osascript');\nosascript.executeFile('path/to/script.scpt', (err, result) => { /* ... */ });"}],"quickstart":{"code":"import osascript from 'node-osascript';\n\nasync function runAppleScriptWithVariables() {\n  const username = process.env.USER ?? 'Guest';\n  const message = `Hello, ${username}! The current time is now:`;\n  const script = `\n    on run {message}\n      set currentTime to (current date) as text\n      display dialog (message & \"\\n\" & currentTime) with title \"Node-osascript Demo\" buttons {\"OK\"} default button \"OK\"\n      set dialogResult to result\n      return \"User clicked \" & (button returned of dialogResult) & \". Script completed at \" & currentTime\n    end run\n  `;\n\n  try {\n    console.log(`Executing AppleScript on behalf of ${username}...`);\n    const [result, raw] = await new Promise((resolve, reject) => {\n      osascript.execute(script, { message }, (err, res, rawRes) => {\n        if (err) return reject(err);\n        resolve([res, rawRes]);\n      });\n    });\n    console.log(\"Parsed Result:\", result); // e.g., \"User clicked OK. Script completed at...\"\n    console.log(\"Raw AppleScript Output:\", raw); // Full stdout from osascript\n  } catch (error) {\n    console.error(\"AppleScript execution failed:\", error);\n    if (error.code === 1) {\n      console.error(\"Hint: This often means a syntax error in your AppleScript or a permission issue.\");\n    }\n  }\n}\n\nrunAppleScriptWithVariables();","lang":"javascript","description":"Demonstrates executing AppleScript with dynamically injected JavaScript variables, handling asynchronous results, and basic error trapping. This showcases the core `execute` method and variable passing."},"warnings":[{"fix":"Ensure your application environment is macOS. For cross-platform desktop applications, consider alternatives like Electron's `shell.openExternal` or native OS APIs for basic tasks.","message":"This package relies on `osascript` and is therefore macOS-only. It will not function on Windows, Linux, or other operating systems.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For older Node.js or strict ESM environments, use `const osascript = require('node-osascript');` or investigate dynamic `import()` or `createRequire` for explicit CJS interop.","message":"The library primarily uses a CommonJS module system (i.e., `require`). While Node.js generally supports `require` in ESM contexts, direct `import osascript from 'node-osascript'` might require specific Node.js configuration or transpilation depending on your setup and Node.js version.","severity":"gotcha","affected_versions":"<=2.1.0"},{"fix":"Always sanitize or escape any user-provided data before incorporating it into AppleScript strings. Prefer passing data via the `variables` object where possible, as it typically handles escaping.","message":"Injecting unsanitized user input directly into AppleScript strings can lead to command injection vulnerabilities, allowing malicious users to execute arbitrary commands.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Wrap `osascript.execute` and `osascript.executeFile` in a `new Promise()` to enable `async/await` usage, as demonstrated in the quickstart example. Consider newer alternatives like `@7c/osascript` for native Promise support.","message":"As a legacy library, `node-osascript` relies on older Node.js APIs and callback-based error handling. It does not natively support Promises or async/await, which are standard in modern Node.js development.","severity":"breaking","affected_versions":"<=2.1.0"},{"fix":"Implement robust timeout logic around your `osascript.execute` calls, using `Promise.race` with a `setTimeout` for `async/await` patterns. Be aware that killing the process might leave applications in an undesirable state.","message":"The `osascript` process itself can sometimes hang or take a long time to execute. The package provides a manual `childProcess.kill()` mechanism for timeouts, which is a blunt instrument and may not gracefully handle script state.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'2.1.0':61 '8':65 'abandon':85 'age':89 'ago':67 'allow':29 'appear':78 'appl':120 'applescript':1,19,36,40,100,122 'automat':95 'bidirect':26 'boolean':46 'cadenc':71 'call':113 'code':20 'communic':27 'compar':109 'convers':98 'correspond':50 'current':57 'data':52,107 'date':44 'differenti':92 'direct':21 'enabl':15 'exec':112 'execut':2,17 'explicit':74 'facilit':25 'given':87 'handl':108 'inject':34 'javascript':23,30,51,104,119 'key':91 'last':62 'librari':11 'list':42 'mainten':83 'nativ':103 'node':6 'node-osascript':5 'node.js':4,13 'number':45 'object':105 'osascript':7,123 'peg.js':55 'phase':86 'plain':117 'project':77 'publish':63 'raw':111 'record':43 'releas':70 'result':41,101 'return':116 'script':121 'simplifi':106 'stabl':58 'state':75 'string':47,118 'structur':96 'transform':39 'type':53,97 'typic':115 'use':54 'util':10 'variabl':31 'version':59 'year':66","created_at":"2026-04-20T01:55:32.167744+00:00","updated_at":"2026-04-20T01:55:32.167744+00:00","problems":[{"fix":"Ensure your application is running on a macOS environment. Verify that `/usr/bin/osascript` exists and is accessible, and that `/usr/bin` is included in your system's PATH. If on a server, confirm macOS is the OS.","cause":"The `osascript` command-line tool, which is part of macOS, could not be found in the system's PATH. This typically happens when running on a non-macOS system, or if the PATH environment variable is misconfigured.","error":"Error: spawn osascript ENOENT"},{"fix":"Use `const osascript = require('node-osascript');` (CommonJS) or `import osascript from 'node-osascript';` (ESM) and then call `osascript.execute(...)`.","cause":"This usually indicates an incorrect import or require statement. The `node-osascript` package exports a single object, and `execute` is a method on that object, not a named export.","error":"TypeError: osascript.execute is not a function"},{"fix":"Carefully review your AppleScript for syntax errors. Test the script directly in Script Editor on macOS to debug any issues before incorporating it into your Node.js code. Ensure applications targeted by the script are installed and running.","cause":"The AppleScript code passed to `execute` or `executeFile` contains a syntax error, or refers to an application/element that does not exist on the system.","error":"Error: Command failed: osascript ... (with AppleScript syntax error)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/FWeinb/node-osascript","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/node-osascript","openapi_spec":null,"status_page":null,"smithery":null,"categories":[],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}