Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

alfy

> 编程语言
Open source

Create Alfred workflows with ease

2.7K stars0 likes2 views
WebsiteGitHub

About

Create Alfred workflows with ease

Create Alfred workflows with ease

Highlights

  • Easy input↔output.
  • Config and cache handling built-in.
  • Fetching remote files with optional caching.
  • Publish your workflow to npm.
  • Automatic update notifications.
  • Easily testable workflows.
  • Finds the node binary.
  • Support for top-level await.
  • Presents uncaught exceptions and unhandled Promise rejections to the user.
    No need to manually .catch() top-level promises.

Prerequisites

You need Node.js 18+ and Alfred 4 or later with the paid Powerpack upgrade.

Install

bash
npm install alfy

Usage

IMPORTANT: Your script will be run as ESM.

  1. Create a new blank Alfred workflow.

  2. Add a Script Filter (right-click the canvas → Inputs → Script Filter), set Language to /bin/bash, and add the following script:

./node_modules/.bin/run-node index.js "$1"

We can't call node directly as GUI apps on macOS doesn't inherit the $PATH.

Tip: You can use generator-alfred to scaffold out an alfy based workflow. If so, you can skip the rest of the steps, go straight to the index.js and do your thing.

  1. Set the Keyword by which you want to invoke your workflow.

  2. Go to your new workflow directory (right-click on the workflow in the sidebar → Open in Finder).

  3. Initialize a repo with npm init.

  4. Add "type": "module" to package.json.

  5. Install Alfy with npm install alfy.

  6. In the workflow directory, create a index.js file, import alfy, and do your thing.

Example

Here we fetch some JSON from a placeholder API and present matching items to the user:

javascript
import alfy from 'alfy';

const data = await alfy.fetch('https://jsonplaceholder.typicode.com/posts');

const items = alfy
	.inputMatches(data, 'title')
	.map(element => ({
		title: element.title,
		subtitle: element.body,
		arg: element.id
	}));

alfy.output(items);
More

Some example usage in the wild: alfred-npms, alfred-emoj, alfred-ng.

Update notifications

Alfy uses alfred-notifier in the background to show a notification when an update for your workflow is available.

Caching

Alfy offers the possibility of caching data, either with the fetch or directly through the cache object.

An important thing to note is that the cached data gets invalidated automatically when you update your workflow. This offers the flexibility for developers to change the structure of the cached data between workflows without having to worry about invalid older data.

Publish to npm

By adding alfy-init as postinstall and alfy-cleanup as preuninstall script, you can publish your package to npm instead of to Packal. This way, your packages are only one simple npm install command away.

json
{
	"name": "alfred-unicorn",
	"version": "1.0.0",
	"description": "My awesome unicorn workflow",
	"author": {
		"name": "Sindre Sorhus",
		"email": "[email protected]",
		"url": "https://sindresorhus.com"
	},
	"scripts": {
		"postinstall": "alfy-init",
		"preuninstall": "alfy-cleanup"
	},
	"dependencies": {
		"alfy": "*"
	}
}

Tip: Prefix your workflow with alfred- to make them easy searchable through npm.

You can remove these properties from your info.plist file as they are being added automatically at install time.

After publishing your workflow to npm, your users can easily install or update the workflow.

bash
npm install --global alfred-unicorn

Tip: instead of manually updating every workflow yourself, use the alfred-updater workflow to do that for you.

Testing

Workflows can easily be tested with alfy-test. Here is a small example.

javascript
import test from 'ava';
import alfyTest from 'alfy-test';

test('main', async t => {
	const alfy = alfyTest();

	const result = await alfy('workflow input');

	t.deepEqual(result, [
		{
			title: 'foo',
			subtitle: 'bar'
		}
	]);
});

Debugging

When developing your workflow it can be useful to be able to debug it when something is not working. This is when the workflow debugger comes in handy. You can find it in your workflow view in Alfred. Press the insect icon to open it. It will show you the plain text output of alfy.output() and anything you log with alfy.log() or console.error():

javascript
import alfy from 'alfy';

const unicorn = getUnicorn();
alfy.log(unicorn);

// You can also use console.error() for debugging
console.error('Debug info:', {data: someData});

Environment variables

Alfred lets users set environment variables for a workflow which can then be used by that workflow. This can be useful if you, for example, need the user to specify an API token for a service. You can access the workflow environment variables from process.env. For example process.env.apiToken.

API

alfy

input

Type: string

Input from Alfred. What the user wrote in the input box.

output(list, options?)

Return output to Alfred.

list

Type: object[]

List of object with any of the supported properties.

Example:

javascript
import alfy from 'alfy';

alfy.output([
	{
		title: 'Unicorn'
	},
	{
		title: 'Rainbow'
	}
]);
options

Type: object

rerunInterval

Type: number (seconds)
Values: 0.1...5.0

A script can be set to re-run automatically after some interval. The script will only be re-run if the script filter is still active and the user hasn't changed the state of the filter by typing and triggering a re-run. More info.

For example, it could be used to update the progress of a particular task:

javascript
import alfy from 'alfy';

alfy.output(
	[
		{
			title: 'Downloading Unicorns…',
			subtitle: `${progress}%`,
		}
	],
	{
		// Re-run and update progress every 3 seconds.
		rerunInterval: 3
	}
);
variables

Type: object

Variables passed out of the script filter and accessible throughout the current session as environment variables. These are session-level variables that persist for the duration of the user action. Individual items can also have their own variables which override these when selected.

javascript
import alfy from 'alfy';

alfy.output(
	[
		{
			title: 'Unicorn',
			arg: 'unicorn',
		}
	],
	{
		variables: {animal: 'unicorn'}
	}
);

log(value)

Log value to the Alfred workflow debugger.

matches(input, list, item?)

Returns a string[] of items in list that case-insensitively contains input.

javascript
import alfy from 'alfy';

alfy.matches('Corn', ['foo', 'unicorn']);
//=> ['unicorn']
input

Type: string

Text to match against the list items.

list

Type: string[]

List to be matched against.

item

Type: string | Function

By default, it will match against the list items.

Specify a string to match against an object property:

javascript
import alfy from 'alfy';

const list = [
	{
		title: 'foo'
	},
	{
		title: 'unicorn'
	}
];

alfy.matches('Unicorn', list, 'title');
//=> [{title: 'unicorn'}]

Or nested property:

javascript
import alfy from 'alfy';

const list = [
	{
		name: {
			first: 'John',
			last: 'Doe'
		}
	},
	{
		name: {
			first: 'Sindre',
			last: 'Sorhus'
		}
	}
];

alfy.matches('sindre', list, 'name.first');
//=> [{name: {first: 'Sindre', last: 'Sorhus'}}]

Specify a function to handle the matching yourself. The function receives the list item and input, both lowercased, as arguments, and is expected to return a boolean of whether it matches:

javascript
import alfy from 'alfy';

const list = ['foo', 'unicorn'];

// Here we do an exact match.
// `Foo` matches the item since it's lowercased for you.
alfy.matches('Foo', list, (item, input) => item === input);
//=> ['foo']

inputMatches(list, item?)

Same as matches(), but with alfy.input as input.

If you want to match against multiple items, you must define your own matching function (as shown here). Let’s extend the example from the beginning to search for a keyword that appears either within the title or body property or both.

javascript
import alfy from 'alfy';

const data = await alfy.fetch('https://jsonplaceholder.typicode.com/posts');

const items = alfy
	.inputMatches(
		data,
		(item, input) =>
			item.title?.toLowerCase().includes(input) ||
			item.body?.toLowerCase().includes(input)
	)
	.map((element) => ({
		title: element.title,
		subtitle: element.body,
		arg: element.id,
	}));

alfy.output(items);

error(error)

Display an error or error message in Alfred.

Note: You don't need to .catch() top-level promises. Alfy handles that for you.

error

Type: Error | string

Error or error message to be displayed.

fetch(url, options?)

Returns a Promise that returns the body of the response.

url

Type: string

URL to fetch.

options

Type: object

Any of the got options and the below options.

json

Type: boolean
Default: true

Parse response body with JSON.parse and set accept header to application/json.

maxAge

Type: number

Number of milliseconds this request should be cached.

resolveBodyOnly

Type: boolean
Default: true

Whether to resolve with only body or a full response.

javascript
import alfy from 'alfy';

await alfy.fetch('https://api.foo.com');
//=> {foo: 'bar'}

await alfy.fetch('https://api.foo.com', {
	resolveBodyOnly: false 
});
/*
{
	body: {
		foo: 'bar'
	},
	headers: {
		'content-type': 'application/json'
	}
}
*/
transform

Type: Function

Transform the response body before it gets cached.

javascript
import alfy from 'alfy';

await alfy.fetch('https://api.foo.com', {
	transform: body => {
		body.foo = 'bar';
		return body;
	}
})

Transform the response.

javascript
import alfy from 'alfy';

await alfy.fetch('https://api.foo.com', {
	resolveBodyOnly: false,
	transform: response => {
		response.body.foo = 'bar';
		return response;
	}
})

You can also return a Promise.

javascript
import alfy from 'alfy';
import xml2js from 'xml2js';
import pify from 'pify';

const parseString = pify(xml2js.parseString);

await alfy.fetch('https://api.foo.com', {
	transform: body => parseString(body)
})

config

Type: object

Persist config data.

Exports a conf instance with the correct config path set.

Example:

javascript
import alfy from 'alfy';

alfy.config.set('unicorn', '');

alfy.config.get('unicorn');
//=> ''

userConfig

Type: Map

Exports a Map with the user workflow configuration. A workflow configuration allows your users to provide configuration information for the workflow. For instance, if you are developing a GitHub workflow, you could let your users provide their own API tokens.

See [alfred-config](https://github.com/SamVerschu

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScriptalfredalfred-workflowalfred3-workflowalfy

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言