Skip to content

Libraries API

Martin Kopischke edited this page Oct 12, 2020 · 2 revisions

Table of Contents

CLI

Libraries/CLI.jxa:13-13

macOS native command line functionality.

Because app.doShellScript doesn’t really cut it.

Meta

runTask

Libraries/CLI.jxa:66-102

Synchronous command line task running based on NSTask: no quoting needed, no expansion of shell variables happening. Note NSTask.currentDirectoryPath, NSTask.launchPath and NSTask.launch are deprecated as of macOS 10.13. See https://stackoverflow.com/a/47315339 for the NSURL based replacement API used here.

Parameters

  • what (string | Path) Path to the task executable to launch.

  • args (string | Array<string>)? Argument(s) to pass to the executable, one array element per shell word.

  • options object? Options for handling the task launch.

    • options.pwd (string | Path)? Working directory for the task.
    • options.env object? Environment to set for the task.
    • options.input string? Data to pipe into stdin.
  • Throws Error NSTask launch errors.

Returns TaskResult The task execution result.

which

Libraries/CLI.jxa:116-126

Locate an executable using which.

Parameters

  • what string The executable to look for.

  • options object? Options affecting which behaviour.

    • options.quiet boolean Return a boolean indicating search success. (optional, default false)
  • Throws Error If what could not be located and options.quiet is falsy.

Returns (string | boolean) The path to the located executable, or whether it is found, depending on options.quiet.

Meta

  • since: 1.3.0

TaskResult

Libraries/CLI.jxa:66-102

Task result object.

Type: object

Properties

  • outText string The standard output of the task.
  • errText string The standard error of the task.
  • exitCode number The task’s exit code.

FileManager

Libraries/FileManager.jxa:13-13

macOS native file system item handling.

Because using System events is slow and cumbersome, and the Finder is both limited and noisy (“sproing”).

Meta

copy

Libraries/FileManager.jxa:53-68

Copy a file system item, bypassing the Finder.

Parameters

  • path (string | Path) Path to the file system item to copy.

  • target (string | Path) Path to the location to copy the item to. If this is a directory, the item will be copied to it under its original name; if not, the item is copied to the full path specification.

  • options object? Copy operation options.

    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs copying the item, unless options.quiet is truthy.

Returns Path? The path to the copied item, or undefined on failure with options.quiet set.

Meta

  • since: 3.0.0

move

Libraries/FileManager.jxa:85-100

Move a file system item, bypassing the Finder.

Parameters

  • path (string | Path) Path to the file system item to move.

  • target (string | Path) Path to the location to move the item to. If this is a directory, the item will be copied to it under its original name; if not, the item is moved to the full path specification.

  • options object? Move operation options.

    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs moving the item, unless options.quiet is truthy.

Returns Path? The path to the moved item, or undefined on failure with options.quiet set.

rename

Libraries/FileManager.jxa:118-136

Rename a file system item, bypassing the Finder. Name and extension are handled separately; where they are nulled, the values from the source item are used (omitting both will make renaming a no-op).

Parameters

  • path (string | Path) Path to the file system item to rename.

  • name string? New name of the item (does not include the extension).

  • extension string? New extension of the item.

  • options object? Move operation options.

    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs renaming the item, unless options.quiet is truthy.

Returns Path? The path to the renamed item, or undefined on failure with options.quiet set.

remove

Libraries/FileManager.jxa:150-160

Delete a file system item, bypassing the macOS trash.

Parameters

  • path (string | Path) Path to the file system item to delete.

  • options object? Removal operation options.

    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs removing the item, unless options.quiet is truthy.

Returns boolean? Success of the operation; note false is only returned on failure if options.quiet is set.

trash

Libraries/FileManager.jxa:174-184

Puts a file system item into the macOS trash, bypassing the Finder.

Parameters

  • path (string | Path) Path to the file system item to delete.

  • options object? Trash operation options.

    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs trashing the item, unless options.quiet is truthy.

Returns boolean Success of the operation; note false is only returned on failure if options.quiet is set.

alias

Libraries/FileManager.jxa:203-223

Create a Finder alias to a file system item.

Parameters

  • path (string | Path) Path to the file system item the alias will point to.

  • target (string | Path) Path to the alias. If this is a directory, the alias will created there under the original item's name; if not, the alias will be created with the full path specification.

  • options object? Alias operation options.

    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs aliasing the item, unless options.quiet is truthy.

Returns Path? The path to the created alias, or undefined on failure with options.quiet set. note false is only returned on options.quiet.

link

Libraries/FileManager.jxa:241-256

Create a symbolic link to a file system item.

Parameters

  • path (string | Path) Path to the file system item the link will point to.

  • target (string | Path) Path to the alias. If this is a directory, the link will created there under the original item's name; if not, the alias will be created with the full path specification.

  • options object? Alias operation options.

    • options.quiet boolean Return false on error (optional, default false)
  • Throws Error When an error occurs linking the item, unless options.quiet is truthy.

Returns Path? The path to the created symlink, or undefined on failure with options.quiet set.

listDirectory

Libraries/FileManager.jxa:270-283

List the file system contents of a directory.

Parameters

  • path (string | Path) Full path of the directory to list.

  • options object? List operation options.

    • options.hidden boolean Show hidden file system items. (optional, default false)
    • options.quiet boolean Return an empty Array on error. (optional, default false)
  • Throws Error When an error occurs listing the directory contents, unless options.quiet is truthy.

Returns Array<Path> The directory contents.

makeDirectory

Libraries/FileManager.jxa:298-310

Create a directory.

Parameters

  • path (string | Path) Path to the directory to create.

  • options object? Creation operation options.

    • options.intermediates boolean Return false error (optional, default false)
    • options.quiet boolean Return false on error (optional, default false)
  • Throws Error When an error occurs creating the directory, unless options.quiet is truthy.

Returns boolean Success of the operation; note false is only returned on options.quiet.

getProperties

Libraries/FileManager.jxa:363-424

Get a file system item’s properties. Note we cannot include the access and addition dates of an item because unwrapping NSDate references returned by NSURL.getResourceValueForKeyError crashes the whole JXA script runtime in an unrecoverable way, and NSFileManager has no API to access these dates.

Parameters

  • path (Path | string) The path to the file system item to retrieve the properties information about.

  • Throws Error When the properties of the item cannot be retrieved.

Returns FSPropertiesObject The file system item’s properties.

FSOwnerObject

Libraries/FileManager.jxa:363-424

Owner information for a file system item.

Type: object

Properties

FSPropertiesObject

Libraries/FileManager.jxa:363-424

Properties of a file system item.

Type: object

Properties

  • owner FSOwnerObject The user owning the item.
  • group FSOwnerObject The group owning the item.
  • permissions number The POSIX permissions mask of the item.
  • fileSize number The size of the item, in bytes (does not include folder contents).
  • extendedAttributes object Extended file system attributes of the item.
  • isDirectory boolean Is the item a directory?
  • isPackage boolean Is the item a macOS package?
  • isFile boolean Is the item a regular file?
  • isAlias boolean Is the item a Finder alias?
  • isSymlink boolean Is the item a symbolic link?
  • isReadable boolean Can the current user read the item?
  • isWritable boolean Can the current user write the item?
  • isDeletable boolean Can the current user delete the item?
  • isExecutable boolean Can the current user delete the item?
  • isHidden boolean Is the item hidden from display?
  • isQuarantined boolean Is the item quarantined by macOS?
  • dateCreated Date Creation date (ctime) of the item.
  • dateModified Date Last modification date (mtime) of the item.
  • displayName string Localised name of the item.
  • displayParts Array<string> User visible parts of the path to the item.
  • typeUTI string Item type key (UTI).
  • typeName string Item type localised name.
  • quarantineData object macOS quarantine properties of the item.

FinderTags

Libraries/FinderTags.jxa:10-10

macOS native Finder tagging functionality.

Meta

getTags

Libraries/FinderTags.jxa:26-37

Get the Finder tags of a file system item.

Parameters

  • path (string | Path) The path to the file system item.

  • options object? Reading operation options.

    • options.quiet boolean Return an empty Array if an error occurs. (optional, default false)
  • Throws Error When an error occurs reading the tags, unless options.quiet is truthy.

Returns string The tags of the object.

setTags

Libraries/FinderTags.jxa:51-63

Set the Finder tags of a file system item, overwriting existing tags.

Parameters

  • path (string | Path) The path to the file system item.

  • tags (string | Array<string>) The tags to set.

  • options object? Tagging operation options.

    • options.quiet boolean Return false if an error occurs. (optional, default false)
  • Throws Error When an error occurs setting the tags, unless options.quiet is truthy.

Returns Array<string> The tags set for path, or undefined if the operation failed and options.quiet is truthy.

addTags

Libraries/FinderTags.jxa:77-84

Add Finder tags to a file system item.

Parameters

  • path (string | Path) The path to the file system item.

  • tags (string | Array<string>) The tags to add.

  • options object? Tagging operation options.

    • options.quiet boolean Return false if an error occurs. (optional, default false)
  • Throws Error When an error occurs adding the tags, unless options.quiet is truthy.

Returns Array<string> The tags set for path, or undefined if the operation failed and options.quiet is truthy.

removeTags

Libraries/FinderTags.jxa:98-102

Remove specific Finder tags from a file system item.

Parameters

  • path (string | Path) The path to the file system item.

  • tags (string | Array<string>) The tags to remove.

  • options object? Tagging operation options.

    • options.quiet boolean Return false if an error occurs. (optional, default false)
  • Throws Error When an error occurs removing the tags, unless options.quiet is truthy.

Returns Array<string> The tags set for path, or undefined if the operation failed and options.quiet is truthy.

clearTags

Libraries/FinderTags.jxa:115-117

Remove all Finder tags from a file system item.

Parameters

  • path (string | Path) The path to the file system item.

  • options object? Tagging operation options.

    • options.quiet boolean Return false if an error occurs. (optional, default false)
  • Throws Error When an error occurs removing the tags, unless options.quiet is truthy.

Returns Array<string> The tags set for path, or undefined if the operation failed and options.quiet is truthy.

JXA

Libraries/JXA.jxa:22-22

JXA Runtime injection functionality.

The OSA library inclusion mechanism is somewhat limited insofar as it only returns functions and cannot cross language boundaries. That makes it unsuited to add JS constants and classes, and to handle Cocoa objects. It is also separating runtime spaces, meaning you cannot patch the JXA runtime from libraries to remedy any of the mentioned issues. This library offers a delivery way for JS injection code stored in .jxa files in the Script Library locations recognised by OS X / MacOS.

Examples

// This monkey patches the `Path` object.
// Using `Function()` is recommended over using `eval()`.
const jxa = Library('JXA')
var _p = new Function(jxa.source('Path')); _p(); _p = null

Meta

paths

Libraries/JXA.jxa:41-74

Get all existing paths where a JXA library module might be located.

Returns Array<Path> The existing search paths for modules.

locate

Libraries/JXA.jxa:84-99

Locate a JXA library module by name.

Parameters

  • name string The name of the module to locate.
  • all string? Whether to return all located library instances.

Returns (Path | Array<Path>) first found location, or all locations if all is truthy.

source

Libraries/JXA.jxa:122-134

Get the literal contents of a JXA library module identified by name. Notes:

  • module files must be text files in a supported encoding;
  • module files must have the extension .jxa;
  • module files must be located in a supported OSA Script Library directory, but:
  • module files cannot be located inside other application bundles. Caveat: there is an issue where Script Editor will lock up when trying to display the return value of a source call. This happens consistently for some files, but damned if I know why (happens with some files that are shorter than files that do not exhibit the issue; with some pure ASCII files and some UTF-8 files, not with others; happens depending on file content, not file name).

Parameters

  • name string The name of the module to locate.

  • Throws Error When unable to read the file contents.

  • Throws RangeError When unable to locate the module.

Returns string Code literal.

Meta

  • since: 2.0.0

Network

Libraries/Network.jxa:10-10

macOS native network functionality.

Meta

hasInternetConnection

Libraries/Network.jxa:24-30

Check if there is internet connectivity.

Returns boolean Is there internet connectivity?

PDFFile

Libraries/PDFFile.jxa:10-10

macOS native PDF functionality.

Meta

isReadable

Libraries/PDFFile.jxa:44-46

Check if a PDF file’s contents are readable.

Parameters

  • path (string | Path) Path to the PDF document.
  • password string Password to use to unlock the document.

Returns boolean Are the contents readable?

getText

Libraries/PDFFile.jxa:59-68

Get a PDF file’s text.

Parameters

  • path (string | Path) Path to the PDF document.
  • options object? Options for the reading operation.
    • options.password string? Password to use to unlock the document.
    • options.objects boolean Include object embed placeholders? (optional, default false)
    • options.compact boolean Strip empty pages? (optional, default false)

Returns string The file text, or undefined if the PDF could not be unlocked.

getProperties

Libraries/PDFFile.jxa:85-95

Get a PDF file’s properties.

Parameters

  • path (string | Path) Path to the PDF document.

Returns PDFProperties The PDF file properties.

pageCount

Libraries/PDFFile.jxa:108-127

Get a PDF file’s page count.

Parameters

  • path (string | Path) Path to the PDF document.
  • options object? Options for the reading operation.
    • options.password string? Password to use to unlock the document.
    • options.text boolean Include text pages? (optional, default true)
    • options.objects boolean Include object embed pages? (optional, default true)

Returns number The page count, or undefined if the PDF could not be unlocked.

PDFProperties

Libraries/PDFFile.jxa:85-95

The properties of a PDF file.

Type: object

Properties

  • encrypted boolean Is the PDF encrypted?
  • copyable boolean Is the PDF copyable?
  • version string The PDF version.
  • attributes object The PDF document attributes.

Process

Libraries/Process.jxa:14-14

macOS native process information functionality.

Meta

info

Libraries/Process.jxa:37-43

Get information about the current process.

Returns ProcInfo The process information.

args

Libraries/Process.jxa:53-58

Return the arguments passed to the current process. Note argv[0] is the first passed argument, NOT the path to the process.

Returns Array<string> The arguments.

Meta

  • since: 2.0.0

env

Libraries/Process.jxa:67-69

Return environment variables for the current application.

Returns object Keyed on the environment variable names.

Meta

  • since: 2.0.0

ProcInfo

Libraries/Process.jxa:37-43

Process information.

Type: object

Properties

  • name string The process name.
  • path Path The process' location in the file system.
  • id number The process identifier.

Spotlight

Libraries/Spotlight.jxa:10-10

macOS native file search functionality.

Meta

find

Libraries/Spotlight.jxa:107-183

Run a Spotlight query in (a) designated location(s). Unlike with the MDQuery API, sorting on 'kMDItemPath' actually works.

Parameters

  • query string The Spotlight query to use.

  • locations (string | Array<string>) The kMDQueryScope(s) to search. (optional, default 'kMDQueryScopeAllIndexed')

  • matchValues (string | Array<string>) The kmDItem* value(s) to retrieve. (optional, default 'kMDItemPath')

  • sortedBy string? The kmDItem* metadata value(s) to sort results by.

  • maxResults number? The maximum number of matches to return (all if unspecified).

  • Throws Error When en error occurs executing the query.

Returns Array<object> The matches for the query, keyed on matchValues.

metadata

Libraries/Spotlight.jxa:192-200

Get the Spotlight metadata for a file system item.

Parameters

  • path (string | Path) Path to the file system object.

Returns object The Spotlight metadata for the item.

System

Libraries/System.jxa:10-10

macOS native system functionality.

Meta

pathTo

Libraries/System.jxa:32-36

Get the path(s) for a system folder in the designated domain(s). For more convenience retrieving some often queried user directories, see the pathToUser* functions below.

Parameters

  • folder number The NSSearchPathDirectory to look up.
  • domains number An OR’ed bit mask of NSSearchPathDomainMask domains.

Returns Array<Path> The matching path(s).

pathToUserHome

Libraries/System.jxa:44-46

Get the path to the current user’s Home directory.

Returns Path The matching path.

pathToUserDocuments

Libraries/System.jxa:54-56

Get the path to the current user’s Documents directory.

Returns Path The matching path.

pathToUserDesktop

Libraries/System.jxa:64-66

Get the path to the current user’s Desktop directory.

Returns Path The matching path.

pathToUserDownloads

Libraries/System.jxa:74-76

Get the path to the current user’s Downloads directory.

Returns Path The matching path.

pathToUserLibrary

Libraries/System.jxa:84-86

Get the path to the current user’s Library directory.

Returns Path The matching path.

pathToTempDirectory

Libraries/System.jxa:94-96

Get the path to the current user’s Temp directory.

Returns Path The matching path.

versionString

Libraries/System.jxa:104-106

Get the OS version info in string form.

Returns string The OS version string.

versionInfo

Libraries/System.jxa:114-118

Get the OS version info in Object form.

Returns object The OS version.

versionAtLeast

Libraries/System.jxa:129-136

Check if the OS version is at least as specified.

Parameters

  • major number The major OS version number to check. (optional, default 0)
  • minor number The minor OS version number to check. (optional, default 0)
  • patch number The patch OS version number to check. (optional, default 0)

Returns boolean Is the OS version at least as specified?

versionCompare

Libraries/System.jxa:157-170

Compare OS version info. Follows sort() semantics (i.e. returns < 0 if the compared version is smaller than the OS one, 0 if identical, > 0 if it is greater than the OS one). Missing or nulled arguments will be ignored for comparison purposes.

Parameters

  • major number? The major OS version number to compare.
  • minor number? The minor OS version number to compare.
  • patch number? The patch OS version number to compare.

Examples

Comparison results

const sys = Library('System')
// on macOS 10.12.5
sys.versionCompare(10, 12, 5)   // => 0
sys.versionCompare(10, 13)      // => 1
sys.versionCompare(10, null, 5) // => 0
sys.versionCompare()            // => undefined

Returns number The comparison result according to sort() semantics.

TextFile

Libraries/TextFile.jxa:10-10

macOS native plain text file handling.

Meta

read

Libraries/TextFile.jxa:25-33

Read a plain text file’s content, detecting its encoding if needed.

Parameters

  • path (string | Path) Path to the file to read.

  • encoding string? Use this NSStringEncoding when reading the file.

  • Throws Error When an error occurs reading the file.

Returns string The contents of the file.

write

Libraries/TextFile.jxa:48-58

Write a String to a plain text file. Existing files are overwritten.

Parameters

  • text string Text contents to write to file.

  • path (string | Path) Path to the file to write.

  • options object? Write options.

    • options.atomic boolean Write the file atomically. (optional, default true)
    • options.encoding number NS*Encoding to use for writing. (optional, default NSUTF8StringEncoding)
    • options.quiet boolean Return false on error. (optional, default false)
  • Throws Error When an error occurs writing the file, unless options.quiet` is truthy.

Returns boolean Success of the write; note false is only returned on options.quiet.

encoding

Libraries/TextFile.jxa:68-76

Detect the encoding of a plain text file.

Parameters

  • path (string | Path) Path to the file to read.

  • Throws Error When an error occurs reading the file.

Returns number The corresponding NSStringEncoding value.

TextParser

Libraries/TextParser.jxa:10-10

macOS native text parsing functionality.

Meta

constants

Libraries/TextParser.jxa:89-91

Get the relevant NSLinguistic* constants across to JXA. Needed as Library() only exposes functions.

Returns TextParserConstants The full set of TextParser constants.

language

Libraries/TextParser.jxa:132-138

Detect the dominant language of a string.

Parameters

  • string string The string to analyse.

Returns string A two-letter language code (or undefined if unsuccessful).

tokenizers

Libraries/TextParser.jxa:147-152

Get all available tokenisers for a designated language.

Parameters

  • language string? Two-letter code. Defaults to the current locale's language.

Returns Array<string> The available NSLinguisticTagSchemes.

tokenize

Libraries/TextParser.jxa:170-183

Tokenise a string with a designated scheme.

Parameters

  • string string The string to tokenise.
  • scheme string The NSLinguisticTagScheme to use for the analysis.

Returns Array<Token> The tokens.

extractAddresses

Libraries/TextParser.jxa:200-202

Get all address tokens from a string.

Parameters

  • fromString string The string to tokenise.

Returns Array<AddressMatch> All token matches.

extractDates

Libraries/TextParser.jxa:219-221

Get all date tokens from a string.

Parameters

  • fromString string The string to tokenise.

Returns Array<DateMatch> All token matches.

extractPhoneNumbers

Libraries/TextParser.jxa:256-258

Get all phone number tokens from a string.

Parameters

  • fromString string The string to tokenise.

Returns Array<PhoneNumberMatch> All token matches.

extractTransitInfo

Libraries/TextParser.jxa:275-277

Get all transit info tokens from a string.

Parameters

  • fromString string The string to tokenise.

Returns Array<TransitInfoMatch> All token matches.

TextParserConstants

Libraries/TextParser.jxa:26-79

TextParser constants.

Type: object

Properties

Token

Libraries/TextParser.jxa:170-183

Token object returned when tokenising a string.

Type: object

Properties

  • kind string The token kind.
  • index number The start index of the token in the source string.
  • value string The string matching the token.

AddressMatch

Libraries/TextParser.jxa:200-202

Address data found in a string.

Type: object

Properties

  • data Array<string> The detected address components.
  • index number The index of the match in the source string.
  • raw string The matched source string.

DateMatch

Libraries/TextParser.jxa:219-221

Date found in a string.

Type: object

Properties

  • data Date The detected Date.
  • index number The index of the match in the source string.
  • raw string The matched source string.

LinkMatch

Libraries/TextParser.jxa:237-239

Link found in a string.

Type: object

Properties

PhoneNumberMatch

Libraries/TextParser.jxa:256-258

Phone number found in a string.

Type: object

Properties

  • data string The detected phone number.
  • index number The index of the match in the source string.
  • raw string The matched source string.

TransitInfoMatch

Libraries/TextParser.jxa:275-277

Transit info data found in a string.

Type: object

Properties

  • data Array<string> The detected transit info components.
  • index number The index of the match in the source string.
  • raw string The matched source string.
Clone this wiki locally