Is it possible to write to a file (on a disk) using JavaScript?

后端 未结 9 1107
走了就别回头了
走了就别回头了 2020-11-28 14:51

I am a novice-intermediate programmer taking a stab at AJAX. While reading up on JavaScript I found it curious that most of the examples I\'ve been drawing on use PHP for su

相关标签:
9条回答
  • 2020-11-28 14:54

    Yes, of course you can. It just depends on what API objects your javascript engine makes available to you.

    However, odds are the javascript engine you're thinking about does not provide this capability. Definitely none of the major web browsers will allow it.

    0 讨论(0)
  • 2020-11-28 14:54

    If you just need to let user download a file (.txt, .csv, images and others) via browser download dialog, you can use data URIs with <a href=... download=.../> tag.

    For example (for text file):

    <a href="data:text/plain;charset=utf-8,TEXT_HERE" download="filename.txt"> Click to download </a>
    

    You can also set the attribute href and download using javascript, and use element.click() to trigger the download.

    However, this method cannot write a file without user confirming the file download dialog.

    0 讨论(0)
  • 2020-11-28 14:55

    No. You could use JavaScript to create an AJAX request to a server-side processing script, but allowing JS to directly write to disk - either client-side or server-side - would be a massive, nasty, glaring, unforgivable browser security hole.

    0 讨论(0)
  • 2020-11-28 15:05

    The short answer is no; you cannot by default write a file to the local disk, by using plain JavaScript in a browser. You'll need a helper to do that. For example, TiddlyWiki is a wiki engine that is just a single, static HTML file, but it can write itself to disk with the help of a Java applet (Tiddly Saver).

    0 讨论(0)
  • 2020-11-28 15:06

    Nope, Javascript is not allowed to access the filesystem at all, its a security restriction in the browser. The only way you can really do it is with ActiveX, but then your limiting yourself to using IE.

    Edit: AS the above post states, it could be possible if your engine allowed it, however I don't know of one browser engine (which is what I asusme you are writing it for) that will allow you to.

    0 讨论(0)
  • 2020-11-28 15:08

    You can use something like Google Gears to produce JS applications which are capable of storing data in a local cache or database. You can't read or write arbitrary areas of the disk though. (This was written in 2009 - Google Gears is now deprecated)

    These days, you should be looking at the local storage capabilities provided by HTML5

    0 讨论(0)
提交回复
热议问题