小编nwe*_*rle的帖子

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

如果我使用standardadditions编写文本文件,我显然可以在参数包中配置编码.在AppleScript中,我会编写«class utf8»但在JXA中使用哪个值?我试过Strings"UTF8","utf8","class utf8"但没有成功.错误总是:"错误:无法转换类型.( - 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);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

在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)
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,下面的例子应该可行,因为约定如何在桥中命名ObjectiveC方法(删除冒号,添加camelcase),但事实并非如此.没有写入文件且返回值为false. …

applescript utf-8 osx-yosemite javascript-automation

7
推荐指数
2
解决办法
1040
查看次数