6

I want to write into txt of any file from chrome(All version) using html5 and javascript or jquery.

I have tried FileSystem API and code I tried is:

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 not working.

Is there any way to write into the file?

Bhumi Shah
  • 8,514
  • 5
  • 54
  • 88
  • Any error thrown? And is it desktop chrome.v13 or +? – choz Mar 19 '16 at 05:26
  • No error but the file is not created even console.log is not displayed anything. Chrome version is 45 – Bhumi Shah Mar 19 '16 at 05:31
  • @BhumiShah Is requirement to prompt user to download created file ? – guest271314 Mar 22 '16 at 04:24
  • No, It is background process, save the data into the file exist in folder. – Bhumi Shah Mar 22 '16 at 08:56
  • @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 ? – guest271314 Mar 22 '16 at 15:54
  • _"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 ? – guest271314 Mar 22 '16 at 16:18
  • Hi @BhumiShah It's really really nice to see you again after a long time(almost a year) I hope you remember me . I hope i can hep you again if you tell me why you need to use a File – bugwheels94 Mar 27 '16 at 22:15
  • @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:// URL – Bhumi Shah Mar 29 '16 at 04:43

1 Answers1

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

Community
  • 1
  • 1
guest271314
  • 1
  • 10
  • 82
  • 156
  • This code console log "unknow error" and no file generated. I have run this code using file://folder/test.html. is this correct? – Bhumi Shah Mar 19 '16 at 07:01
  • @BhumiShah Was able to return expected results at chrome 42 at `file:` protocol with `--allow-file-access-from-files` flag set and `localStorage` enabled – guest271314 Mar 19 '16 at 08:13
  • @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 http://plnkr.co to demonstrate ? – guest271314 Mar 19 '16 at 17:49
  • I have tried on version 39,45,48 and laumch command is /usr/bin/google-chrome --allow-access-from-files http://plnkr.co/edit/ETlOjuSsONXqFaWzS6K9?p=info – Bhumi Shah Mar 21 '16 at 05:54
  • @BhumiShah The launch flag should be `--allow-file-access-from-files` – guest271314 Mar 21 '16 at 06:00
  • @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 http://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview see updated post; could also use `Promise` to call `readFile` only when `writeFile` completes – guest271314 Mar 21 '16 at 06:11
  • I am getting message "Error: Unknown Error test.js:64 Write completed." but log.txt file was not created in the folder. – Bhumi Shah Mar 21 '16 at 06:16
  • @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` ? – guest271314 Mar 21 '16 at 06:17
  • 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. – Bhumi Shah Mar 21 '16 at 06:20
  • @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 http://www.html5rocks.com/en/tutorials/file/filesystem/ – guest271314 Mar 21 '16 at 06:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107005/discussion-between-bhumi-shah-and-guest271314). – Bhumi Shah Mar 22 '16 at 09:52
  • @BhumiShah Initial answer was not accurate. See updated post. – guest271314 Mar 29 '16 at 05:11
  • Yeah i have checked but filesystem will not store the data in specific user directory,right? – Bhumi Shah Mar 29 '16 at 05:14
  • @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 user – guest271314 Mar 29 '16 at 05:25
  • @BhumiShah See also http://stackoverflow.com/questions/19802032/how-can-a-chrome-extension-save-many-files-to-a-user-specified-directory – guest271314 May 06 '16 at 20:11