Since you said you do not plan to host it anywhere you could just move your code into a Packaged app. From there you can use the chrome.fileSystem api.
Use chooseEntry() to ask the user which directory they want the app to be able to read/write to. In the callback check that the returned entry is valid, and then store it for later use.
var userDir = null;
chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function(theEntry) {
//do sanity check(s) and store it
if(!theEntry.isDirectory) {
//report error
return;
}
userDir = theEntry;
});
Once you have a directory entry reference than you can use getFile() to get a reference to a file, creating it if it doesn't already exist, same goes for creating subdirectories just substitute getFile
with getDirectory
. Then use createWriter() get a FileWriter instance to write to that file.
function saveData(filename,data){
if(!userDir) {
//report error
return;
}
userDir.getFile(filename, {create: true}, function(fileEntry) {
if(!fileEntry || !fileEntry.isFile){
//report error
return;
}
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
//report success
};
fileWriter.onerror = function(e) {
//report error: e.toString()
};
//Create a Blob from the data and write it.
var blob = new Blob([data], {type: 'text/plain'});
fileWriter.write(blob);
});
});
}
//at some point after user has selected directory
saveData("log.txt","Some data");
Check the various documentations for error reporting and other necessities.
If you want to only ask the user once for the directory use retainEntry() to save an id of the directory entry. And use restoreEntry() to get the reference back of the directory. From there its just a matter of doing the steps in the saveData function. Check the documentation for other processes like reading the file.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…