Create a file using Javascript in Chrome on client side
Sure you can, using the brand new APIs.
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
fs.root.getFile('test.bin', {create: true}, function(fileEntry) { // test.bin is filename
fileEntry.createWriter(function(fileWriter) {
var arr = new Uint8Array(3); // data length
arr[0] = 97; // byte data; these are codes for 'abc'
arr[1] = 98;
arr[2] = 99;
var blob = new Blob([arr]);
fileWriter.addEventListener("writeend", function() {
// navigate to file, will download
location.href = fileEntry.toURL();
}, false);
fileWriter.write(blob);
}, function() {});
}, function() {});
}, function() {});
How to Create a Text File Locally at client side using JavaScript/JQuery
This is a little tricky but working
chrome.browserAction.onClicked.addListener(createFile);
createFile();
function createFile()
{
chrome.tabs.getSelected(null, function(tab) {
window.webkitRequestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
fs.root.getFile('test', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var builder = new WebKitBlobBuilder();
builder.append("Saurabh");
builder.append("\n");
builder.append("Saxena");
var blob = builder.getBlob('text/plain');
fileWriter.onwriteend = function() {
chrome.tabs.create({"url":fileEntry.toURL(),"selected":true},function(tab){});
};
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}, errorHandler);
});
}
function errorHandler(e) {
var msg = '';
switch (e.code) {
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);
}
Because of the Security Exceptions, i cannot create/modify a file on Local System. But in this code, I am actually creating a file in a directory which is allocated for Google Chrome Temporary Files and then downloading that file into my Downloads Folder.
This is the code of the popup page of a Chrome Extension.
:)
Is it possible to write data to file using only JavaScript?
Some suggestions for this -
- If you are trying to write a file on client machine, 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 file.
- If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
- To store some information on the client side that is considerably small, you can go for cookies.
- Using the HTML5 API for Local Storage.
How to create a file in memory for user to download, but not through server?
You can use data URIs. Browser support varies; see Wikipedia. Example:
<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>
The octet-stream is to force a download prompt. Otherwise, it will probably open in the browser.
For CSV, you can use:
<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>
Try the jsFiddle demo.
Client side file creation and download
you have no way to touch the local disk with Javascript by design.
I think you could pass the whole bunch of data from javascript to the server side code ( php, asp.net, java... ) then you could stream it down to the browser somehow.
Open, create files and save data in client side and reuse that data
You're right that localstorage is not enabled for Chrome packaged apps. However, depending on what kind of data you're managing, there are two APIs that should work.
chrome.storage.local
is a general key-value store that will save data on the local machine (chrome.storage.sync
is an identical API that will also synchronize the data between a users' devices, but I wouldn't recommend it for large files)
The API is simple to use:
chrome.storage.local.set({myKey: "myValue"}, function() {
if (!chrome.runtime.lastError) {
console.log("The value has been stored!");
} else {
console.error("There was an error!");
}
});
chrome.storage.local.get("myKey", function(data) {
if (!chrome.runtime.lastError) {
console.log("The value is " + data.myKey);
} else {
console.error("There was an error!");
}
});
(If you're using chrome.storage.sync, then you probably also want to add a listener to the chrome.storage.onChanged
event, to know when data was changed from another location)
The other way may be what you're thinking of as "plain javascript file IO" -- the W3C File System API is supported by packaged apps. You can request storage space from the user and store actual files that you can read and write in JavaScript. There's a good introduction to it here.
Saving data to a local file using only JavaScript
You can use the Chrome Apps File API, you will need to grant access to the file via a user action once, but after that you can get access the file again by using restoreEntry
Related Topics
Replace All Spaces in a String with '+'
Does JavaScript Process Using an Elastic Racetrack Algorithm
What the Difference Between .Click and .Change on a Checkbox
How Dangerous Is It in JavaScript, Really, to Assume Undefined Is Not Overwritten
Convert an Image into Binary Data in JavaScript
Group by Array and Add Field and Sub Array in Main Array
How to Get the Back Button to Work with an Angularjs Ui-Router State MAChine
Ajax Post and Plus Sign ( + ) -- How to Encode
Tried to Load Angular More Than Once
Why Isn't [1,2,3] Equal to Itself in JavaScript
Getting How Many People Are in a Chat Room in Socket.Io
Browserify, Babel 6, Gulp - Unexpected Token on Spread Operator
Should I Refrain from Handling Promise Rejection Asynchronously