如何使用用于Mac Automation的JavaScript编写UTF-8文件? [英] How can I write UTF-8 files using JavaScript for Mac Automation?
问题描述
简而言之-什么是适用于Mac Automation的JavaScript,相当于AppleScript的as «class utf8»
?
我正尝试使用JavaScript for Mac Automation将Unicode字符串写入文本文件。
将字符串写入文件时,文件中出现的任何Unicode字符都会变成问号(ASCII字符3F
)。
如果这是一个AppleScript脚本而不是JavaScript脚本,我可以通过添加as «class utf8»
raw语句来解决这个问题,如吉田隆的博客(https://takashiyoshida.org/blog/applescript-write-text-as-utf8-string-to-file/)所述。
要编写该文件,我使用的是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文本
- 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
显式指定要使用的编码。最重要的是,从OSX 10.4开始,writeToFile:atomically
就被苹果弃用了。
这篇关于如何使用用于Mac Automation的JavaScript编写UTF-8文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!