JSC: My new friend

Original link: furbo.org/2021/08/25/…

A friend of mine recently recommended a nice hidden command line tool to me. Among the front-end frameworks used in Safari and other parts of Apple’s products is a tool called JSC. It’s a JavaScript command-line interface that uses the same code as the rest of the system.

You can under the path/System/Library/Frameworks/JavaScriptCore framework Versions/Current/Helpers/JSC find this tool of binary files. The path is very verbose, so I gave it a name that lets me quickly enter it by typing JSC in the terminal.

So, what can we do with JSC? You can do a lot of things with JavaScript in a browser, but it’s important to note that there are no instances of Document and Window.

If you run the JSC -h command, you’ll see a number of JavaScript options for testing and analysis. Apparently, the Webkit team uses it internally for testing. But we can still use it to try out our ideas and run simple use cases.

A picture is worth a thousand words, so let me show you how to use it to solve a simple problem. I recently needed to convert some strings in our Turkish Frenzic localization to uppercase: the lowercase “I” will be converted to the dotless version.

ToLocaleUpperCase () in JavaScript is the best way to handle this, so I took JSC out of my toolkit and put it to use. The first challenge is getting input.

Fortunately, the readline() method takes input from the keyboard and returns the value. Unfortunately, the input is not encoded in UTF-8 as expected, but is returned as ISO-8895-1(Latin-1). Remember, there is no document instance, so use the default encoding.

To work around this limitation, you can escape characters to UTF-16 and then decode them to UTF-8 using this technique:

var text = decodeURIComponent(escape(readline()));
Copy the code

(If there were a Webkit engineer reading this, it would be nice to have a command-line option like –encoding= UTF-8.)

The generated output is also a little different from the browser. You will use print() instead of console.log(). To convert text inputs and display them, I use the following code:

print(text.toLocaleUpperCase('tr-TR'));
Copy the code

There are some built-in methods that might prove useful, but for now, I just need to read and write text. Although not recorded, JSC also accepts standard input and can be used like sheBANG:

$ echo "print(1+2);" | jsc
Copy the code

Since I may need to use this part of the code again, I create a turk.js file:

while (true) { print('Turkish text? '); var text = decodeURIComponent(escape(readline())); print(text.toLocaleUpperCase('tr-TR')); print('-------------'); }Copy the code

I can now run this code anytime using JSC Turkish.js. And you’ll see how convenient iT is to use JavaScript on the command line. Enjoy!