javascriptfile-ioout-of-browser

Create a file in JavaScript without web browser


My question is, how do you use JavaScript to create and edit a file on the user's computer when running outside a web browser. I understand this is not possible inside a web browser for security reasons, but when invoked from the command line how can I do this in JavaScript.

Actually, I am not running from the command line I am using Java to evaluate it, but I doubt that would matter. (new ScriptEngineManager().getEngineByName("JavaScript").eval(myCode), if you were wondering how I do it.)


Solution

  • Contrary to anything I would have ever assumed, when running JavaScript from Java with the method I have shown above, the JavaScript will have access to Java's standard libraries. So all that has to be done is var writer = new java.io.PrintWriter(new java.io.File("myFile.txt")); writer.println("Text"); writer.flush(); writer.close();. And that actually works perfectly.

    EDIT:

    Actually, the JavaScript will have access to all the Java classes that your Java application has access too. So any Java libraries you add can also be used within your JS.

    EDIT 2:

    For more information on how Java launched JavaScript behaves, please see this article on the JavaScript engine used to parse it.