Skip to content

Instantly share code, notes, and snippets.

@callionica
Last active November 24, 2017 14:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callionica/899696f3fc1437f2b86e to your computer and use it in GitHub Desktop.
Save callionica/899696f3fc1437f2b86e to your computer and use it in GitHub Desktop.
"use strict";
ObjC.import('Foundation');
var fm = $.NSFileManager.defaultManager;
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var path = $.NSString.alloc.initWithUTF8String(app.pathTo(this)).stringByDeletingLastPathComponent.js + "/";
// Read a UTF8 file at a given path and return a JS string
var read_file = function (path) {
var contents = fm.contentsAtPath(path.toString()); // NSData
contents = $.NSString.alloc.initWithDataEncoding(contents, $.NSUTF8StringEncoding);
return ObjC.unwrap(contents);
};
// Write a UTF8 file at a given path given a JS string
var write_file = function (path, contents) {
var s = ObjC.wrap(contents);
s.writeToFileAtomicallyEncodingError(path.toString(), true, $.NSUTF8StringEncoding, null);
};
// Return an array of strings containing the names of the files within the given directory
var get_files = function (path) {
var files = ObjC.unwrap(fm.contentsOfDirectoryAtPathError(path.toString(), null)).map(function (o) {
return ObjC.unwrap(o);
});
return files;
};
var require = function (path) {
var module = { exports: {} };
var exports = module.exports;
eval(read_file(path));
return module.exports;
};
var alert = function (text, informationalText) {
var options = { };
if (informationalText) options.message = informationalText;
app.displayAlert(text, options);
};
@callionica
Copy link
Author

Here's some minimal code to get started with Javascript for Automation JXA. This gives plain ol' javascript code access to the file system on OS X along with basic implementations of require and alert.

@yoodu
Copy link

yoodu commented Nov 24, 2017

This is very helpful ,Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment