File

The File protocol:

protocol File {
  func save(_ path: String, _ content: String, _ overwrite: Bool = false) -> String?
 
  func read(_ path: String) -> String?
 
  func showInFinder(_ path: String)
 
  func open(_ path: String)
 
  func copy(_ path: String)
}

You can save files to or read files at resources folder in Scripts folder with $file API.

$file.save

let path = '/markdown/hello-world.md';
let content = 'Hello World!';
let realPath = $file.save(path, content); // New file at `/markdown/hello-world.md` or `/markdown/hello-world-4AE49C131DDD.md`

OK JSON will try to create sub folders with the provided path. If the file already exists at the path, random string will be appended to the file name so that your files would not be overwritten.

If you want to overwrite the existing file, pass true as the third argument.

let path = '/markdown/hello-world.md';
let content = 'Hello World!';
let realPath = $file.save(path, content, true); // Overwrite `/markdown/hello-world.md`

$file.save returns the file path, which you can pass to $file.open or $file.showInFinder.

$file.read

let path = '/markdown/hello-world.md';
let content = $file.read(path); // `Hello World!` or `undefined`

Read text file at path. Return undefined if any error is encountered.

$file.showInFinder

let path = '/markdown/hello-world.md';
$file.showInFinder(path);

Show file in Finder. A File Not Found alert will be shown if no file is found at the path.

$file.open

let path = '/markdown/hello-world.md';
$file.open(path);

Open file with default configuration. A File Not Found alert will be shown if no file is found at the path.

$file.copy

let path = '/markdown/hello-world.md';
$file.copy(path);

Copy file at the path.