JXAのコードをnode.jsへ移譲する例 ref: http://qiita.com/tom-u/items/a2b1ad4d208c4720aaba
function nodejs(fn,lp='/usr/local/bin/node') {
let code = `console.log(JSON.stringify((${fn.toString()}).apply(null,JSON.parse(process.env.NODE_ARGS))))`
let data = $(code).dataUsingEncoding($.NSUTF8StringEncoding)
return function(...args) {
let i = $.NSPipe.new
i.fileHandleForWriting.writeData(data)
i.fileHandleForWriting.closeFile
let o = $.NSPipe.new
let e = $.NSPipe.new
let t = $.NSTask.new
t.standardInput = i
t.standardOutput = o
t.standardError = e
t.launchPath = lp
t.environment = $({'NODE_ARGS':JSON.stringify(args)})
t.launch
t.waitUntilExit
return new Promise((res,rej) => {
let out = o.fileHandleForReading.readDataToEndOfFile
if (out.length>0) {
try {
res(JSON.parse($.NSString.alloc.initWithDataEncoding(out,$.NSUTF8StringEncoding).js))
} catch(e) {
rej(e)
}
}
let err = e.fileHandleForReading.readDataToEndOfFile
if (err.length>0) {
rej({
message: $.NSString.alloc.initWithDataEncoding(err,$.NSUTF8StringEncoding).js,
status: t.terminationStatus,
})
}
})
}
}
foo=(x,y)=>x+y
nodejs(foo)(1,1)
.then (console.log)
.catch(r=>console.log('failure',r.message))