JXA:在写入文件时设置 UTF-8 编码



如果我使用标准添加编写文本文件,我显然可以在参数包中配置编码。在AppleScript中,我会写"类utf8",但是在JXA中使用哪个值?我尝试了字符串"UTF8","utf8","类utf8"但没有成功。错误始终为:"错误:无法转换类型。(-1700)".如果我使用"文本",则文件是用MACROMAN编写的。

下面的独立示例:

var exportFileWriter = fileWriter('/Users/norman/mini.txt');
exportFileWriter.write('äöü');
exportFileWriter.close();

function fileWriter(pathAsString) {
    'use strict';
    var app = Application.currentApplication();
    app.includeStandardAdditions = true;
    var path = Path(pathAsString);
    var file = app.openForAccess(path, {writePermission: true});
    /* reset file length */
    app.setEof(file, {to: 0});
    return {
        write: function(content) {
            /* How can I write UTF-8? */
            app.write(content, {to: file, as: 'text'});
        },
        close: function() {
            app.closeAccess(file);
        }
    };
}

foo回答后的补充:

我阅读了文档中的相关段落 https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/index.html#//apple_ref/doc/uid/TP40014508-CH109-SW17

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instm/NSString/writeToFile:atomically:encoding:error:

改用 ObjectiveC 桥接器。此示例有效

str = $.NSString.alloc.initWithUTF8String('foo')
str.writeToFileAtomically('/tmp/foo', true)

如果我理解正确,以下示例应该有效,因为约定如何在桥中命名 ObjectiveC 方法(删除冒号,添加驼峰),但它没有。未写入任何文件,返回值为 false。

str = $.NSString.alloc.initWithUTF8String('foo')
str.writeToFileAtomicallyEncodingError('/tmp/foo', true, 'UTF-8', null);

我做错了什么?我什至不知道如何将正确的错误处理程序作为第 4 个参数传递,以及第 3 个参数是否具有正确的值。

请尝试

str = $.NSString.alloc.initWithUTF8String('foo');
str.writeToFileAtomicallyEncodingError('/tmp/foo', true, $.NSUTF8StringEncoding, null);

在这里工作!可用的编码列在 NSString 文档中(请参阅您的链接)!
享受, 迈克尔/汉堡

JXA的Apple事件桥有缺陷,有许多残缺和缺失的功能(例如,使用原始AE代码的能力)。改用其 ObjC 桥接器;请参阅-[NSString writeToFile:atomically:encoding:error:]

最新更新