sindresorhus/alfy

How can i output a function?

rawnly opened this issue · 3 comments

Hello! How can i run a function (for example execa) when user select an item from list?

That's my code:

alfy.output([
	{
		title: 'Random',
		body: 'Get random photo'
	}, {
               title: 'ID',
               body: 'Pick photo by id'
        }
])  

Maybe not quite understand how it works

Link your alfred locally (./node_modules/.bin/alfy-init). Open Alfred and open the Workflows section and open your workflow.

You will now see something like this
screen shot 2017-03-04 at 20 46 11

Currently, by default the script passes the selected option to the Open URL action. However, you can remove that action and add another one by right-clicking the screen, Actions -> Run Script. A popup will apear and you can enter a bash command, or if you want to handle it with Node.js, the following script should work as well.

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

Where handler.js is a file in your project

Connect both of them and you're good to go.

screen shot 2017-03-04 at 20 49 39


So how do you pass data from your search view to the handler.js file? Quite simple by adding an arg property to your output list.

alfy.output([
	{
		title: 'Random',
		body: 'Get random photo',
                arg: 'rand'
	}, {
               title: 'ID',
               body: 'Pick photo by id',
               arg: 'id'
        }
])  

And in your handler.js, get the arg value like so

const arg = process.argv[2];

if (arg === 'rand') {
    // Get a random picture
}

Hope this is enough information to get you going.

Yesterday I made alfred-fkill which uses the exact same workflow as I describe above. It might give you some inspiration :).

Thank you very much!