简单地说,什么是Mac自动化的as «class utf8» JavaScript相当于AppleScript的 ?
我有一个unicode字符串,我正试图使用的JavaScript将其写入文本文件。
当将字符串写入文件时,出现的任何unicode字符都会成为文件中的问号(ASCII char 3F)。
如果这是一个AppleScript脚本而不是JavaScript脚本,我可以通过添加as «class utf8»原始语句来解决这个问题,就像Takashi的博客(https://takashiyoshida.org/blog/applescript-write-text-as-utf8-string-to-file/)中解释的那样。
但是,脚本已经用JavaScript编写了,所以我正在寻找与这个AppleScript语句等价的JavaScript。苹果关于原始语句的页面只针对AppleScript (data.html)。
为了编写该文件,我使用了苹果自己的writeTextToFile JavaScript函数示例(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" })并尝试了以下所有字符串(如所写的和小写形式的):
除了"text“(这导致了相同的问号情况)之外,使用上述所有字符串都生成了一个零字节文件。
我知道我可能在这里涉水,但如果有人读过这篇文章,并愿意提供一些指点,我将非常感激。
发布于 2017-05-31 07:59:01
如果要确保文件是用UTF8编码编写的,请使用NSString的writeToFile:atomically:encoding:error函数,如下所示:
fileStr = $.NSString.alloc.initWithUTF8String( 'your string here' )
fileStr.writeToFileAtomicallyEncodingError( filePath, true, $.NSUTF8StringEncoding, $() )您可能会认为,编写从NSString字符串初始化的UTF8对象会被写出为UTF8,但我从经验中发现,writeToFile:atomically并不尊重正在写入的字符串的编码。writeToFile:atomically:encoding:error显式指定要使用哪种编码。更重要的是,自从OSX10.4之后,writeToFile:atomically就遭到了苹果的反对。
发布于 2017-05-31 20:11:46
@PatrickWayne有the correct solution。
我已经在我的库中有了这个函数,所以我想我应该共享它。它使用相同的键命令。
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function writeFile(pPathStr, pOutputStr) { // @File @Write @ObjC
/* VER: 2.0 2017-03-18
---------------------------------------------------------------
PARAMETERS:
pPathStr | string | Path of file to write. May use tilde (~)
pOutputStr | string | String to be output to file.
*/
//--- CONVERT TO NS STRING ---
var nsStr = $.NSString.alloc.initWithUTF8String(pOutputStr)
//--- EXPAND TILDE AND CONVERT TO NS PATH ---
var nsPath = $(pPathStr).stringByStandardizingPath
//--- WRITE TO FILE ---
// Returns true IF successful, ELSE false
var successBool = nsStr.writeToFileAtomicallyEncodingError(nsPath, false, $.NSUTF8StringEncoding, null)
if (!successBool) {
throw new Error("function writeFile ERROR:\nWrite to File FAILED for:\n" + pPathStr)
}
return successBool
};
发布于 2017-05-30 17:48:56
虽然我无法找到只使用JavaScript的方法,但最终我使用了Objective桥来完成UTF-8文件的编写。
这是我使用的代码。这是调用Objective类的NSString代码,它替换了我前面提到的writeTextToFile函数:
objCText = $.NSString.alloc.initWithUTF8String(text);
objCText.writeToFileAtomically(filePathString, true);https://stackoverflow.com/questions/44268436
复制相似问题