Last active
November 24, 2017 14:35
-
-
Save callionica/899696f3fc1437f2b86e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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); | |
}; |
This is very helpful ,Thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.