📌  相关文章
📜  运行一个 applescript - TypeScript (1)

📅  最后修改于: 2023-12-03 14:57:55.513000             🧑  作者: Mango

运行一个 applescript - TypeScript

Applescript is a powerful scripting language used on macOS for automation, task automation, and system administration. TypeScript, on the other hand, is a superset of JavaScript that adds features like static typing, classes, and interfaces. In this article, we will explore how to run an Applescript file from a TypeScript program.

Prerequisites

To run an Applescript file from a TypeScript program, you need:

  • A macOS computer
  • Node.js installed on your computer
  • Basic knowledge of TypeScript and Applescript
Steps
  1. Create a new TypeScript project using the following command:
$ mkdir applescript-ts && cd applescript-ts
$ npm init -y
$ npm install -D typescript ts-node
  1. Create a new applescript.ts file in your project directory and add the following code:
import * as childProcess from 'child_process';

const applescript = `
  tell application "Finder"
    set myFolder to choose folder with prompt "Choose a folder:"
    display dialog "You chose " & POSIX path of myFolder
  end tell
`;

childProcess.execSync(`osascript -e '${applescript}'`);
  1. Compile and run the TypeScript file using the following command:
$ npx ts-node applescript.ts
  1. Choose a folder when prompted, and the path to the folder will be displayed in a dialog box.
Explanation

The child_process module in Node.js allows us to execute shell commands from our TypeScript program. We use the execSync method to execute the osascript command, which allows us to run Applescript commands from the command line.

We pass our Applescript code as a string to the osascript command using backticks and the $ symbol. We also use the tell block to specify the target application for our script, which in this case is the Finder app.

In our example, we display a prompt to choose a folder, and then we display the path to the chosen folder in a dialog box using display dialog.

Conclusion

Running an Applescript file from a TypeScript program can be a powerful tool for macOS automation. By following the steps outlined in this article, you can easily integrate Applescript into your TypeScript projects.