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

10
如果我使用标准附加项编写文本文件,我显然可以在参数包中配置编码。在AppleScript中,我会写«class utf8»,但是在JXA中使用哪个值呢?
我尝试了字符串"UTF8"、"utf8"、"class utf8",但都没有成功。错误始终为:"Error: Can't convert types. (-1700)"。如果我使用"text",则文件将以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);

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

2个回答

10

请尝试

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

在这里工作过!可用的编码在NSString文档中列出(请参阅您的链接)!
祝好,Michael / Hamburg


赶我一步!我刚想发布相同的答案,这个答案也对我有用。 - Justin Putney
谢谢。它运行良好。如果我有足够的声望,我会为您和foo的答案点赞。 在foo提出ObjC Bridge之前,我的解决方法是使用node.js并要求“encoding”:encoding.convert(data,'UTF-8','MACROMAN')。 来自苏黎世到汉堡的问候。 - nwehrle

4

JXA的苹果事件桥存在许多缺陷和缺失功能(例如,无法使用原始AE代码)。相反,请使用其ObjC桥;请参见- [NSString writeToFile:atomically:encoding:error:]


感谢您的输入。我阅读了一些文档,编辑了我的问题并添加了一些最小示例。 - nwehrle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接