Question

I have a small script made with JXA (JavaScript for Automation) that outputs a result to the shell with console.log.

However, console.log seems to output to stderr and I’d like to output to stdout. I can always 2>&1 when calling the script, but it would be preferable to output directly to stdout from the script.

Is there a way to accomplish that?

Was it helpful?

Solution

Found the solution: don’t use console.log or anything else. Instead of

console.log('something');

Simply

'something';

It will be output to stdout.

OTHER TIPS

It may not be the prettiest solution ever, but I think your best bet is to use the Objective-C scripting bridge. The alternative would be to deal directly with the command line and printf, which would probably be even messier.

Using the scripting bridge, you can re-assign console.log to a custom function that writes to stdout using NSFileHandle.fileHandleWithStandardOutput. If you put this definition at the top of your program, you can then use this revised console.log.

console.log = function() {
    ObjC.import('Foundation');
    for (argument of arguments) {
        $.NSFileHandle.fileHandleWithStandardOutput.writeData($.NSString.alloc.initWithString(String(argument) + "\n").dataUsingEncoding($.NSNEXTSTEPStringEncoding));
    }
}

Note that I've added a line break at the end of each string—you may want to customize this behavior to meet your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with apple.stackexchange
scroll top