简体   繁体   English

如何使用 JavaScript 读写文件?

[英]How to read and write into file using JavaScript?

Can anybody give some sample code to read and write a file using JavaScript?任何人都可以提供一些示例代码来使用 JavaScript 读写文件吗?

For completeness, the OP does not state he is looking to do this in a browser (if he is, as has been stated, it is generally not possible)为了完整起见,OP 没有 state 他希望在浏览器中执行此操作(如果他是,如前所述,通常是不可能的)

However javascript per se does allow this;但是 javascript 本身确实允许这样做; it can be done with server side javascript.它可以通过服务器端 javascript 来完成。

See this documentation on the Javascript File class 请参阅 Javascript 文件 class 的此文档

Edit : That link was to the Sun docs that now have been moved by Oracle.编辑:该链接指向现在已由 Oracle 移动的 Sun 文档。

To keep up with the times here's the node.js documentation for the FileSystem class: http://nodejs.org/docs/latest/api/fs.html To keep up with the times here's the node.js documentation for the FileSystem class: http://nodejs.org/docs/latest/api/fs.html

Edit(2) : You can read files client side now with HTML5: http://www.html5rocks.com/en/tutorials/file/dndfiles/编辑(2) :您现在可以使用 HTML5 在客户端读取文件: http://www.html5rocks.com/en/tutorials/file/dndfiles/

No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled没有。浏览器端 javascript 没有权限写入客户端计算机,无需禁用许多安全选项

The future is here, The proposals are closer to completion.未来已来,提案更接近完成。 no more ActiveX or flash or java: Now we can use:不再有 ActiveX 或 flash 或 java:现在我们可以使用:

You could use the Drag/Drop to get the file into the browser, or a simple upload control.您可以使用拖放将文件放入浏览器,或使用简单的上传控件。 Once the user has selected a file, you can read it w/ Javascript: http://www.html5rocks.com/en/tutorials/file/dndfiles/用户选择文件后,您可以使用 Javascript 阅读它: http://www.html5rocks.com/en/tutorials/file/dndfiles/

here's the mozilla proposal这是 Mozilla 提案

http://www-archive.mozilla.org/js/js-file-object.html http://www-archive.mozilla.org/js/js-file-object.html

this is implemented with a compilation switch in spidermonkey, and also in adobe's extendscript.这是通过 spidermonkey 和 adobe 的扩展脚本中的编译开关实现的。 Additionally (I think) you get the File object in firefox extensions.此外(我认为)您在 firefox 扩展中获得文件 object。

rhino has a (rather rudementary) readFile function https://developer.mozilla.org/en/Rhino_Shell rhino 有一个(相当粗略的)readFile function https://developer.mozilla.org/en/Rhino_Shell

for more complex file operations in rhino, you can use java.io.File methods.对于 rhino 中更复杂的文件操作,可以使用 java.io.File 方法。

you won't get any of this stuff in the browser though.但是,您不会在浏览器中获得任何这些东西。 For similar functionality in a browser you can use the SQL database functions from HTML5, clientside persistence, cookies, and flash storage objects.对于浏览器中的类似功能,您可以使用来自 HTML5、客户端持久性、cookies 和 ZA408AA7012725AEAB41 存储对象的 SQL 数据库函数。

This Javascript function presents a complete "Save As" Dialog box to the user who runs this through the browser.这个 Javascript function 向通过浏览器运行它的用户提供了一个完整的“另存为”对话框。 The user presses OK and the file is saved.用户按 OK 并保存文件。

Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.编辑:以下代码仅适用于 IE 浏览器,因为 Firefox 和 Chrome 已将此代码视为安全问题并阻止其工作。

// content is the data you'll write to file<br/>
// filename is the filename<br/>
// what I did is use iFrame as a buffer, fill it up with text
function save_content_to_file(content, filename)
{
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename+'.txt');
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function:调用 function:

save_content_to_file("Hello", "C:\\test");

If you are using JScript (Microsoft's Javascript) to do local scripting using WSH (NOT in a browser!) you can use Scripting.FileSystemObject to access the file system.如果您使用 JScript(Microsoft 的 Javascript)使用 WSH(不在浏览器中!)执行本地脚本,您可以使用Scripting.FileSystemObject来访问文件系统。

I think you can access that same object in IE if you turn a lot of security settings off, but that would be a very, very bad idea.我认为如果您关闭许多安全设置,您可以在 IE 中访问相同的 object,但这将是一个非常非常糟糕的主意。

MSDN hereMSDN在这里

Currently, files can be written and read from the context of a browser tab/window with the File , FileWriter , and FileSystem APIs, though there are caveats to their use (see tail of this answer).目前,可以使用FileFileWriterFileSystem API 从浏览器选项卡/窗口的上下文中写入和读取文件,尽管它们的使用有一些注意事项(请参阅此答案的尾部)。

But to answer your question:但要回答你的问题:

Using BakedGoods *使用烘焙食品*

Write file:写入文件:

bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

Read file:读取文件:

bakedGoods.get({
        data: ["testFile"],
        storageTypes: ["fileSystem"],
        options: {fileSystem:{storageType: Window.PERSISTENT}},
        complete: function(resultDataObj, byStorageTypeErrorObj){}
});

Using the raw File, FileWriter, and FileSystem APIs使用原始 File、FileWriter 和 FileSystem API

Write file:写入文件:

function onQuotaRequestSuccess(grantedQuota)
{

    function saveFile(directoryEntry)
    {

        function createFileWriter(fileEntry)
        {

            function write(fileWriter)
            {
                var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
                fileWriter.write(dataBlob);              
            }

            fileEntry.createWriter(write);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: true, exclusive: true},
            createFileWriter
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Read file:读取文件:

function onQuotaRequestSuccess(grantedQuota)
{

    function getfile(directoryEntry)
    {

        function readFile(fileEntry)
        {

            function read(file)
            {
                var fileReader = new FileReader();

                fileReader.onload = function(){var fileData = fileReader.result};
                fileReader.readAsText(file);             
            }

            fileEntry.file(read);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: false},
            readFile
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Just what you asked for right?正是你要求的对吗? Maybe, maybe not.也许,也许不是。 The latter two of the APIs:后两个 API:

  • Are currently only implemented in Chromium-based browsers (Chrome & Opera)目前仅在基于 Chromium 的浏览器(Chrome 和 Opera)中实现
  • Have been taken off the W3C standards track, and as of now are proprietary APIs已脱离 W3C 标准轨道,目前是专有 API
  • May be removed from the implementing browsers in the future将来可能会从实施浏览器中删除
  • Constrict the creation of files to a sandbox (a location outside of which the files can produce no effect) on disk将文件的创建限制在磁盘上的沙箱(文件在其之外不会产生影响的位置)

Additionally, the FileSystem spec defines no guidelines on how directory structures are to appear on disk.此外,文件系统规范没有定义目录结构在磁盘上的显示方式。 In Chromium-based browsers for example, the sandbox has a virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser), within which the directories and files created with the APIs are placed.例如,在基于 Chromium 的浏览器中,沙箱有一个虚拟文件系统(一个目录结构,它不一定以与从浏览器中访问时相同的形式存在于磁盘上),其中使用放置 API。

So though you may be able to write files to a system with the APIs, locating the files without the APIs (well, without the FileSystem API) could be a non-trivial affair.因此,尽管您可以使用 API 将文件写入系统,但在没有 API(好吧,没有 FileSystem API)的情况下定位文件可能不是一件容易的事。

If you can deal with these issues/limitations, these APIs are pretty much the only native way to do what you've asked.如果您可以处理这些问题/限制,那么这些 API 几乎是完成您所要求的事情的唯一本地方式。

If you're open to non-native solutions, Silverlight also allows for file i/o from a tab/window contest throughIsolatedStorage .如果您对非本地解决方案持开放态度,Silverlight 还允许通过IsolatedStorage从选项卡/窗口竞赛中进行文件 i/o。 However, managed code is required to utilize this facility;但是,需要托管代码才能使用此功能; a solution which requires writing such code is beyond the scope of this question.需要编写此类代码的解决方案超出了此问题的 scope 范围。

Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question;):当然,使用补充托管代码的解决方案,只留下 Javascript 来编写,完全在这个问题的 scope 之内;):

//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem", "silverlight"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

* BakedGoods is a Javascript library that establishes a uniform interface that can be used to conduct common storage operations in all native, and some non-native storage facilities. * BakedGoods 是一个 Javascript 库,它建立了一个统一的接口,可用于在所有本地和一些非本地存储设施中进行常见的存储操作。 It is maintained by this guy right here: ).它是由这个人在这里维护的:)。

For Firefox:对于 Firefox:

var file = Components.classes["@mozilla.org/file/local;1"].
       createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");

Seehttps://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O请参阅https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O

For others, check out the TiddlyWiki app to see how it does it.对于其他人,请查看TiddlyWiki应用程序以了解它是如何做到的。

In the context of browser, Javascript can READ user-specified file.在浏览器的上下文中,Javascript 可以读取用户指定的文件。 See Eric Bidelman's blog for detail about reading file using File API.有关使用文件 API 读取文件的详细信息,请参阅Eric Bidelman 的博客 However, it is not possible for browser-based Javascript to WRITE the file system of local computer without disabling some security settings because it is regarded as a security threat for any website to change your local file system arbitrarily.但是,基于浏览器的Javascript不可能在不禁用某些安全设置的情况下写入本地计算机的文件系统,因为任何网站随意更改本地文件系统都被视为安全威胁。

Saying that, there are some ways to work around it depending what you are trying to do:话虽如此,有一些方法可以解决它,具体取决于您要执行的操作:

  1. If it is your own site, you can embed a Java Applet in the web page.如果是自己的站点,可以在web页面中嵌入一个Java小程序。 However, the visitor has to install Java on local machine and will be alerted about the security risk.但是,访问者必须在本地机器上安装 Java 并且会收到有关安全风险的警报。 The visitor has to allow the applet to be loaded.访问者必须允许加载小程序。 An Java Applet is like an executable software that has complete access to the local computer. Java Applet 就像一个可执行软件,可以完全访问本地计算机。

  2. Chrome supports a file system which is a sandboxed portion of the local file system. Chrome 支持的文件系统是本地文件系统的沙盒部分。 See this page for details.有关详细信息,请参阅此页面 This provides possibly for you to temporarily save things locally.这为您提供了在本地临时保存东西的可能。 However, this is not supported by other browsers.但是,其他浏览器不支持此功能。

  3. If you are not limited to browser, Node.js has a complete file system interface.如果不局限于浏览器,Node.js 有完整的文件系统接口。 See here for its file system documentation .有关其文件系统文档,请参见此处。 Note that Node.js can run not only on servers, but also any client computer including windows.请注意,Node.js 不仅可以在服务器上运行,还可以在任何客户端计算机上运行,包括 windows。 The javascript test runner Karma is based on Node.js. javascript 测试运行器 Karma 基于 Node.js。 If you just like to program in javascript on the local computer, this is an option.如果您只是想在本地计算机上的 javascript 中编程,这是一个选项。

To create file try创建文件尝试

function makefile(){
  var fso;
  var thefile;

    fso = new ActiveXObject("Scripting.FileSystemObject");
    thefile=fso.CreateTextFile("C:\\tmp\\MyFile.txt",true);

    thefile.close()
    }

Create your directory in the C drive because windows has security against writing from web eg create folder named "tmp" in C drive. Create your directory in the C drive because windows has security against writing from web eg create folder named "tmp" in C drive.

You'll have to turn to Flash, Java or Silverlight.您将不得不求助于 Flash、Java 或 Silverlight。 In the case of Silverlight, you'll be looking at Isolated Storage .对于 Silverlight,您将看到独立存储 That will get you write to files in your own playground on the users disk.这将使您在用户磁盘上自己的操场上写入文件。 It won't let you write outside of your playground though.但它不会让你在操场外写作。

From a ReactJS test, the following code successfully writes a file:从 ReactJS 测试中,以下代码成功写入文件:

import writeJsonFile from 'write-json-file';

const ans = 42;
writeJsonFile('answer.txt', ans);

const json = {"answer": ans};
writeJsonFile('answer_json.txt', json);

The file is written to the directory containing the tests, so writing to an actual JSON file '*.json' creates a loop!该文件被写入包含测试的目录,因此写入实际的 JSON 文件“*.json”会创建一个循环!

You can't do this in any cross-browser way.您不能以任何跨浏览器的方式执行此操作。 IE does have methods to enable "trusted" applications to use ActiveX objects to read/write files, but that is it unfortunately. IE 确实有一些方法可以使“受信任的”应用程序使用 ActiveX 对象来读/写文件,但不幸的是它就是这样。

If you are looking to save user information, you will most likely need to use cookies.如果您希望保存用户信息,您很可能需要使用 cookies。

Writing this answer for people who wants to get a file to download with specific content from javascript.为想要从 javascript 下载包含特定内容的文件的人编写此答案。 I was struggling with the same thing.我也在为同样的事情而苦苦挣扎。

const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile';                     //filename to download
a.click();

Check Blob documentation here - Blob MDN在此处查看 Blob 文档 - Blob MDN

There are two ways to read and write a file using JavaScript使用 JavaScript 读写文件有两种方式

  1. Using JavaScript extensions使用 JavaScript 扩展

  2. Using a web page and Active X objects使用 web 页面和 Active X 对象

You cannot do file i/o on the client side using javascript as that would be a security risk.您不能使用 javascript 在客户端执行文件 i/o,因为这会带来安全风险。 You'd either have to get them to download and run an exe, or if the file is on your server, use AJAX and a server-side language such as PHP to do the i/o on serverside您必须让他们下载并运行 exe,或者如果文件在您的服务器上,请使用 AJAX 和服务器端语言(例如 PHP)在服务器端执行 i/o

Here is write solution for chrome v52+ (user still need to select a destination doe...)这是 chrome v52+ 的编写解决方案(用户仍然需要 select 目标 doe...)
source: StreamSaver.js来源: StreamSaver.js

<!-- load StreamSaver.js before streams polyfill to detect support -->
<script src="StreamSaver.js"></script>
<script src="https://wzrd.in/standalone/web-streams-polyfill@latest"></script>
const writeStream = streamSaver.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024)
let uint8array = encoder.encode(data + "\n\n")

writeStream.write(uint8array) // must be uInt8array
writeStream.close()

Best suited for writing large data generated on client side.最适合编写在客户端生成的大数据。
Otherwise I suggest using FileSaver.js to save Blob/Files否则我建议使用FileSaver.js来保存 Blob/Files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM