How to write into a file (in user directory) using JavaScript?
Asked Answered
S

1

7

I want to write text into any file from Chrome (all version) using HTML5 and JavaScript or jQuery.

I have tried using the FileSystem API:

function onFs(fs) {
 console.log('test');
  fs.root.getFile('log.txt', {create: true, exclusive: true},
      function(fileEntry) {
        // fileEntry.isFile === true
        // fileEntry.name == 'log.txt'
        // fileEntry.fullPath == '/log.txt'

        fileEntry.getMetaData(function(md) {
          console.log(md.modificationTime.toDateString());
        }, onError);

      },
      onError
  );
}

window.webkitRequestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs);

But it's not working.

Is there any way to write into the file?

Smoker answered 19/3, 2016 at 5:13 Comment(7)
Any error thrown? And is it desktop chrome.v13 or +?Burkett
No error but the file is not created even console.log is not displayed anything. Chrome version is 45Smoker
@BhumiShah Is requirement to prompt user to download created file ?Norland
No, It is background process, save the data into the file exist in folder.Smoker
@BhumiShah "save the data into the file exist in folder" are you referencing the TEMPORARY filesystem created by window.requestFileSystem at filesystem: protocol, or , for example , ~/Downloads directory of user filesystem ?Norland
"I want to create a file(log/txt etc) in user specified directory to log the details using js file and also read data from sh file." How does user specifiy file ? What do you mean by read from .sh file ?Norland
@user1533609: I want to store log into file of each activity that's why I want to store it in file and its local system so I don't have http:// URLSmoker
N
4

I want to write file in user directory

You cannot directly write file to user filesystem .

After searching SO for similar Questions to accurately resolve Question, was able to $ cat contents of file created at plnkr following this answer posted by @Iain at Where does PERSISTENT file system storage store with chrome? . The file was written to the user filesystem at ~/.config/[chrome, chromium] directory.

Used file manager to navigate to

  ~/.config/[chrome, chromium]/Default/File System

to review the directory; the file containing text written below, was found in a folder having two digits as a folder name, then within two further sub-directories; a sub-directory having a single lowercase letter as folder name; within this sub-directory there was another sub-directory having two digits as a folder name; the file that was written by window.webkitRequestFileSystem had eight digits as a file name, without an extension, though having correct "text/plain" MIME type; set at Blob type property.

Then at terminal

  $ cd ~/.config/[chrome, chromium]/Default/File\ System/[three digits]/[lowercase letter]/[two digits]

  $ cat [eight digits]
  Lorem Ipsum

Have not tried to create a .sh file and execute it. Would probably require placing the directory in path or moving the file to a folder in existing path; set appropriate permissions for file. Could possibly adjust this at chrome / chromium browser settings, though have not tried this either.

You could probably write a command to copy or move the file at /path/to/file to an folder in path, and execute the file; or other approach.


You can use download attribute of a element to allow download of file created by createWriter to user filesystem.

The file system is sandboxed

Because the file system is sandboxed, a web app cannot access another app's files. You also cannot read or write files to an arbitrary folder (for example, My Pictures and My Documents) on the user's hard drive.

see also at Definititons

persistent storage Persistent storage is storage that stays in the browser unless the user expunges it or the app deletes it.
temporary storage Transient storage is available to any web app. It is automatic and does not need to be requested, but the browser can delete the storage without warning.


I want to write file in user directory because it has to be user understandable.

Edit, Updated

You can use the method described above. That is, use a file manager at to review how the folders and files appear in

  ~/.config/[chrome, chromium]/Default/File System

  ## do stuff with contents of file written by `window.requestFilesystem`

To view file in chrome / chromium FileSystem you can navigate to DevTools -> Experiments -> check FileSystem inspection , log.txt should be listed at Resources tab at FileSystem .

Can also navigate to file at address bar using URL

filesystem:http://run.plnkr.co/temporary/log.txt

which should have contents

Lorem Ipsum

or

filesystem:http://run.plnkr.co/temporary/

to view all files and directories in root of temporary filesystem

See Exploring the FileSystem API

First launch chrome / chromium with --allow-file-access-from-files flag , see How do I make the Google Chrome flag "--allow-file-access-from-files" permanent? .

Next

window.requestFileSystem  = window.requestFileSystem 
                            || window.webkitRequestFileSystem;

add error handling

function errorHandler(e) {
  var msg = '';

  switch (e.message) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

You should then be able to

function writeFile(fs) {

  fs.root.getFile('log.txt', {create: true}, function(fileEntry) {

    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function(fileWriter) {

      fileWriter.onwriteend = function(e) {
        console.log('Write completed.');
        // call `readFile` here
        window.requestFileSystem(window.TEMPORARY, 1024*1024, readFile, errorHandler);

      };

      fileWriter.onerror = function(e) {
        console.log('Write failed: ' + e.toString());
      };

      // Create a new Blob and write it to log.txt.
      var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});

      fileWriter.write(blob);

    }, errorHandler);

  }, errorHandler);

}

window.requestFileSystem(window.TEMPORARY, 1024*1024, writeFile, errorHandler);

function readFile(fs) {

  fs.root.getFile('log.txt', {}, function(fileEntry) {

    // Get a File object representing the file,
    // then use FileReader to read its contents.
    fileEntry.file(function(file) {
       var reader = new FileReader();

       reader.onloadend = function(e) {
         console.log(e.target.result)
       };

       reader.readAsText(file);
    }, errorHandler);

  }, errorHandler);

}

plnkr http://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview


Note, at Chrome 38+ it is also possible to create a File object using the new File() constructor; see Chrome: Create file input from blob with Javascript? .

No, It is background process, save the data into the file exist in folder.

This approach, too, will not automatically write created file to an existing folder at user filesystem.

With either approach user action should be required to save file to user filesystem. This can be achieved using download attribute at a element , data URI How to export JavaScript array info to csv (on client side)? , or an iframe element Download File Using Javascript/jQuery ; which should prompt user to either select to save file or not save file.


See also The FileSaver interface , FileSaver.js

Norland answered 19/3, 2016 at 6:25 Comment(15)
This code console log "unknow error" and no file generated. I have run this code using file://folder/test.html. is this correct?Smoker
@BhumiShah Was able to return expected results at chrome 42 at file: protocol with --allow-file-access-from-files flag set and localStorage enabledNorland
@BhumiShah "I have tried but getting same error." Which version of chrome ? Can you include launch command for chrome at Question ? Can you create a plnkr plnkr.co to demonstrate ?Norland
I have tried on version 39,45,48 and laumch command is /usr/bin/google-chrome --allow-access-from-files plnkr.co/edit/ETlOjuSsONXqFaWzS6K9?p=infoSmoker
@BhumiShah The launch flag should be --allow-file-access-from-filesNorland
@BhumiShah Also the callback for getFile is asynchronous. Calling readFile without waiting for writeFile to complete may cause error. Called readFile within writeFile callback at plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview see updated post; could also use Promise to call readFile only when writeFile completesNorland
I am getting message "Error: Unknown Error test.js:64 Write completed." but log.txt file was not created in the folder.Smoker
@BhumiShah "but log.txt file was not created in the folder." What do you mean by "not created in folder" ? Files created using .createWriter are not written to user filesystem . Is "Lorem Ipsum" logged at console ?Norland
I mean how can I check the log.txt file? I want to write file in user directory because it has to be user understandable.Smoker
@BhumiShah "I want to write file in user directory" You cannot directly write file to user filesystem . You can offer download of created file to user. To view file in chrome FileSystem you can navigate to DevTools -> Experiments -> check FileSystem inspection , log.txt should be listed at Resources tab at FileSystem . See also html5rocks.com/en/tutorials/file/filesystemNorland
Let us continue this discussion in chat.Smoker
@BhumiShah Initial answer was not accurate. See updated post.Norland
Yeah i have checked but filesystem will not store the data in specific user directory,right?Smoker
@BhumiShah At *nix the file, by default, appears to be saved to a sub-directory at ~/.config/chromium/Default/File System . This could probably be adjusted by userNorland
@BhumiShah See also #19802532Norland

© 2022 - 2024 — McMap. All rights reserved.