user3359826
user3359826

Reputation:

JXA: move or duplicate files

I’m trying to do a very simple thing — move (or duplicate) a file using JavaScript for Automation introduced with OS X Yosemite.

So far I have something like this.

finder = Application("Finder")

finder.move(Path("/Users/user/Source/file.pdf"), {
    to: Path("/Users/user/Destination/file.pdf"),
    replacing: true
})

The result is not great.

Error -1728: Can't get object.

Of course I can just use something like doShellScript("mv source destination") but Finder + JAX solution seems to be better.

Upvotes: 2

Views: 2454

Answers (3)

kopischke
kopischke

Reputation: 3413

Finder’s move and duplicate actions work just fine with JXA Path objects. The reason your code fails it that the to argument these actions expect is a path to a folder while you are providing the path to a file. This will work:

finder = Application("Finder")

finder.move(Path("/Users/user/Source/file.pdf"), {
    to: Path("/Users/user/Destination/"),
    replacing: true
})

Upvotes: 3

syntaxera
syntaxera

Reputation: 254

This script works using Finder objects with the move command:

var Finder = Application("Finder")
var homeDirectory = Finder.startupDisk.folders["Users"].folders["user"]

var sourceFile = homeDirectory.folders["Source"].files["file.pdf"]
var destinationFolder = homeDirectory.folders["Destination"]

Finder.move(sourceFile, { to: destinationFolder })

It also works for the duplicate command.

Upvotes: -1

ShooTerKo
ShooTerKo

Reputation: 2282

Yeah, it's a mess with the JXA and the Finder. I think the problem lies in the Finder loving Aliasses etc. against the nontyped variables in JavaScript. First I thought, the problem was that the target file does not exist and then the Path()-call can't return a variable type file. But even if you create an empty target file with that name, the script fails (but with another error message...)

The only way I found out was to use the JXA-ObjC-Bridge as descriptor in the JXA release notes:

ObjC.import('Cocoa')
error = $()
fMa = $.NSFileManager.defaultManager
fileMoved = fMa.moveItemAtPathToPathError('/Users/user/Source/file.pdf','/Users/user/Destination/file.pdf', error)
if (!fileMoved) {
    $.NSBeep();
    // or do something else depending on error.code
}

I think it's a more elegant way than using shell scripting, but that is only a feeling ;-)

Cheers, Michael / Hamburg

Upvotes: 0

Related Questions