1

This is for personal use only, so permissions/security issues can be ignored for the time being.

I have:

A "Create File" button and event listener. I'm able to successfully alert() all the information I need for the path and file name I want created.

I want:

A function to create a local file in a directory as specified by the script, e.g.:

Create "C:\Foo\Bar.txt", where C:\Foo already exists and "Bar.txt" is an empty text file.

2 Answers2

1

so permissions/security issues can be ignored for the time being

No, actually, they can't.

Wishful thinking is nice, but whatever it is you want, you simply can't write to a local filesystem using browser JavaScript, including GreaseMonkey.

The best you can do is allow the user to save the file, by providing a link. The user can right-click and save to a file then.

<a href="data:text/plain;charset=utf-8,test%20contents%0D%0Ago%20here">Saveable</a>

you can set contents with:

function setDownloadableText(aElement, contents) {
  aElement.setAttribute('href', 'data:text/plain;charset=utf-8,' + contents);
}
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • true, one of the big javascript rules: no messing with the file system. – Frank Dec 29 '11 at 21:43
  • @Frank: Almost :) node.js can, browser extensions can. But basically anything user-written is crippled. – Amadan Dec 29 '11 at 21:47
  • I have another Greasemonkey script that opens a file on the user's filesystem. I had to set new user_pref() values in the Profile Directory, but it works. Is a similar workaround for file creation not possible? –  Dec 29 '11 at 21:57
  • 1
    If you already know of such a script, linking to it would have helped. I do not know of a way to do it, and [GreaseMonkey FAQ agrees](http://wiki.greasespot.net/FAQ#Can_Greasemonkey_be_used_to_open_local_files.3F) that it shouldn't be possible. – Amadan Dec 29 '11 at 22:01
  • The trick was to give chrome-level privileges through altering user_prefs. The script just generates a link "file:\\\C:\Etc\Etc" that it opens on your local filesystem instead of in-browser. It sounds like file creation/deletion/modification is not possible, though. –  Dec 29 '11 at 22:43
1

Since you said "permissions/security issues can be ignored for the time being", here's what you can do:

  • Use IE, preferably an older version (this is against all sane advice but you asked for it)
  • Disable restrictions for ActiveX creation (probably the worst thing you can do in IE)
  • Create a "FileSystemObject" instance and call it's "CreateTextFile" method:
var myObject = new ActiveXObject("Scripting.FileSystemObject");    
var newfile = myObject.CreateTextFile("c:\\testing.txt", false);
Abbas
  • 6,720
  • 4
  • 35
  • 49
  • Doesn't work with Greasemonkey! Just kidding... good answer, if you can get your hands on an IE (I can't). – Amadan Dec 29 '11 at 21:49