Javascript Nashorn scripting mode: how to write to file
I'm writing a shell script to be run with jjs -scripting under Java 8. However, a key requirement is that I need to be able to write to a number of files. (So I can't just print() to stdout and redirect.)
There's handily readFully to read a file, but I don't see any writeFully, which seems odd to me.
I thought probably I could just $EXEC an echo command, but I can't get that to work:
jjs> x='some string'
some string
jjs> $EXEC("echo '"+x+"' >test.out");
some string >test.out
So my next thought is that I have to load up and call the appropriate Java classes, but that seems like it's over-complicating a simple function. What am I missing?
Answer
The best I could figure out was to do it via the Java FileWriter class. For example, I had an array of links I needed written to a file:
var FileWriter=Java.type("java.io.FileWriter");
var olinkfile = caldir+"/"+year+"_links.html";
var fw = new FileWriter(olinkfile);
fw.write(links.join("\n"));
fw.write("\n");
fw.close(); // forgetting to close it results in a truncated file
Although it would have been nice for JJS to provide a function to do this directly from JavaScript without having to instantiate the FileWriter class manually, this really isn't too much code. And once you've done it once it seems almost obvious.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM