How to read and write into file using JavaScript?

后端 未结 17 2504
孤街浪徒
孤街浪徒 2020-11-22 02:00

Can anybody give some sample code to read and write a file using JavaScript?

17条回答
  •  旧时难觅i
    2020-11-22 02:34

    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).

    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

    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:

    • Are currently only implemented in Chromium-based browsers (Chrome & Opera)
    • Have been taken off the W3C standards track, and as of now are proprietary APIs
    • 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.

    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.

    If you can deal with these issues/limitations, these APIs are pretty much the only native way to do what you've asked.

    If you're open to non-native solutions, Silverlight also allows for file i/o from a tab/window contest through IsolatedStorage. However, managed code is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.

    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 ;) :

    //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. It is maintained by this guy right here : ) .

提交回复
热议问题