如何使用 JavaScript for Mac Automation 编写 UTF-8 文件?

Ari*_*leo 4 javascript macos applescript javascript-automation

简而言之 - Mac 自动化的 JavaScript 相当于 AppleScript 的as «class utf8»什么?

我有一个 unicode 字符串,我正在尝试使用 JavaScript for Mac Automation 将其写入文本文件。

将字符串写入文件时,任何存在的 unicode 字符都会成为文件中的问号 (ASCII char 3F)。

如果这是一个 AppleScript 脚本而不是 JavaScript 脚本,我可以通过添加as «class utf8»原始语句来解决这个问题,如 Takashi Yoshida 的博客 ( https://takashiyoshida.org/blog/applescript-write-text-as-utf8-string -到文件/)。

但是,该脚本已经用 JavaScript 编写,因此我正在寻找与此 AppleScript 语句等效的 JavaScript。Apple 关于原始语句的页面仅针对 AppleScript ( https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/conceptual/ASLR_raw_data.html )。

要编写文件,我使用 Apple 自己的writeTextToFileJavaScript 函数示例(https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/ReadandWriteFiles.html#//apple_ref/doc/uid/TP40016239- CH58-SW1 )。as根据 StandardAdditions 字典,我向以下调用添加了一个参数:

// Write the new content to the file
app.write(text, { to: openedFile, startingAt: app.getEof(openedFile), as: "utf8" })
Run Code Online (Sandbox Code Playgroud)

并尝试了以下所有字符串(如书面形式和小写形式):

  • Unicode 文本
  • 统一码
  • utf8 类
  • «类utf8»
  • utf8
  • 文本
  • utf8 文本

除了“文本”(导致相同的问号情况),使用上述所有字符串产生一个零字节文件。

我知道我可能会在这里涉足未知的水域,但如果有人读过这篇文章之前已经处理过这个问题并愿意提供一些指导,我将不胜感激

Pat*_*nne 5

如果要确保使用 UTF8 编码写入文件,请使用 NSString 的writeToFile:atomically:encoding:error函数,如下所示:

fileStr = $.NSString.alloc.initWithUTF8String( 'your string here' )
fileStr.writeToFileAtomicallyEncodingError( filePath, true, $.NSUTF8StringEncoding, $() )
Run Code Online (Sandbox Code Playgroud)

您可能会认为编写从 UTF8 字符串初始化的 NSString 对象会被写出为 UTF8,但我从经验中发现writeToFile:atomically不尊重正在写出的字符串的编码。writeToFile:atomically:encoding:error明确指定要使用的编码。最重要的是,writeToFile:atomically自 OS X 10.4 以来,Apple 已弃用。