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

标签 javascript macos applescript javascript-automation

简而言之 - 与 AppleScript 的 as «class utf8» 等效的 Mac Automation JavaScript 是什么?

我有一个 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-to-file/) 中所述。

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

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

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

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

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

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

我知道我可能会涉足这里的未知水域,但是如果阅读本文的任何人以前处理过这个问题并愿意提供一些指导,我将非常感激 😋

最佳答案

如果你想确保你的文件以 UTF8 编码写入,使用 NSString 的 writeToFile:atomically:encoding:error 函数,像这样:

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

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

关于javascript - 如何使用 JavaScript 为 Mac Automation 编写 UTF-8 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44268436/

相关文章:

sed - 在applescript中通过sed用撇号文本替换文本

php - 从 Ruby 或 PHP 或 Cocoa 访问 Mac 应用程序

javascript - 如何维护 Bootstrap 选项卡上的分页?

javascript - 使用 ActiveX DeleteFile 时权限被拒绝

xcode - 升级到 Xcode 4.5 后没有生成的派生数据

macos - 在 NSTextField 上按下 Enter 键时如何做某事

javascript - 将两个 JSON 值合并为一个数组

javascript - 我如何优化这一长行 "if"语句?

linux - 通过 USB 驱动器复制 git repo 会导致所有文件显示为已修改

import - 在另一个AppleScript中导入AppleScript方法吗?