How can I write UTF-8 files using JavaScript for Mac Automation?

后端 未结 4 852
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 15:05

In short - what is the JavaScript for Mac Automation equivalent of AppleScript\'s as «class utf8» ?

I have a unicode string that I\'m t

4条回答
  •  隐瞒了意图╮
    2021-01-13 16:02

    If you want to ensure your file gets written with UTF8 encoding, use NSString's writeToFile:atomically:encoding:error function, like so:

    fileStr = $.NSString.alloc.initWithUTF8String( 'your string here' )
    fileStr.writeToFileAtomicallyEncodingError( filePath, true, $.NSUTF8StringEncoding, $() )
    

    You would think that writing an NSString object initialized from a UTF8 string would get written out as UTF8 but I've found from experience that writeToFile:atomically does not honor the encoding of the string being written out. writeToFile:atomically:encoding:error explicitly specifies which encoding to use. On top of that, writeToFile:atomically has been deprecated by Apple since OS X 10.4.

提交回复
热议问题