Search code examples
javascriptapplescriptautomatorfinder

Run JavaScript "for each file or folder" that's selected in Finder, using a macOS Automator service workflow


Trying to write a service where I can control+click multiple files, run an Automator service that copies the paths to those files to clipboard, and performs a few string replacements.

So here's what I got:

1. The input

the input

2. Run JavaScript

function run(input, parameters) {

    var path = String(input);
    path = path.replace(/^.+\/websites\//, "/"); // this should remove some stuff off the paths up until /websites/

    return path;
}

3. Copy to Clipboard

The problem: Only the last file is copied to clipboard.

How do I fix this so I can select multiple files, have Automator loop over all paths, do the necessary text replacements using JavaScript, and copy all new paths to clipboard ?

I've tried for (path in input) { ... } but then path is a string with input's index value...

PS: How would I do this using AppleScript?


Solution

  • Since this is JavaScript, you have the luxury of using map that means looping in the traditional sense isn't required:

    function run(input) {
        return input.map( fp => fp.replace(/^.+\/websites\//. '/') );
    }
    

    One thing you should check (which I haven't because I'm not completely clear about the context) is that the input receives the paths in posix format, e.g. /path/to/something, rather than the old HFS format, e.g. Macintosh HD:path:to:something.