0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JXAのコードをnode.jsへ移譲する例

Posted at

使用OS: macOS 10.12

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) {
		return new Promise((res,rej) => {
			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
			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))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?