Created
December 15, 2011 14:01
-
-
Save Yoric/1481186 to your computer and use it in GitHub Desktop.
Working out the kinks of OS.File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1. Reading a string from an unopened file | |
/** | |
* @param {string|OS.Path} aSource The file to read | |
* | |
* @return {Promise} The promise of a string. In case of error, the promise is | |
* rejected and holds the exception. | |
*/ | |
function readAll(aSource) { | |
return OS.File.read(aSource).just(function() { | |
return this.readString(); | |
}); | |
} | |
//2. Writing a string to a new file. | |
/** | |
* @param {string|OS.Path} aDest The file to write | |
* | |
* @return {Promise} The promise of the number of bytes written. In case of | |
* error, the promise is rejected and holds the exception. | |
*/ | |
function dumpTo(aContent, aDest) { | |
return OS.File.truncateC(aDest).just(function() { | |
this.writeString(aContent); | |
}); | |
} | |
// or, alternatively, without |just|, | |
function dumpTo(aContent, aDest) { | |
let file; | |
return OS.File.truncateC(aDest).soon(function(aFile) { | |
file = aFile; | |
return file.writeString(aContent); | |
}).always(function(aStatus) { | |
file.close(); | |
}); | |
} | |
//3. Copying an unopened file to another by reading all and writing all | |
function copy(aSource, aDest) { | |
return OS.File.read(aSource). | |
just(OS.File.prototype.readString). | |
soon(function(aContents) { | |
OS.File.truncateC(aDest). | |
return just(OS.File.prototype.writeString, aContents); | |
}); | |
} | |
//4. In the future, possibly, a more reasonable copy operation, by chunks | |
function copy(aSource, aDest, aChunkSize) { | |
//Open both files asynchronously | |
return Promise.group([ OS.File.read(aSourceName), | |
OS.File.truncateC(aDestName) ]). | |
soon(function(files) { | |
let [source, dest] = files; | |
//Connect streams | |
let reader = source.readStringStream(aChunkSize); | |
let writer = dest.writeStringStream(); | |
return OS.File.pump(reader, writer). | |
//Don't forget closing | |
always(source.close). | |
always(dest.close); | |
}); | |
} | |
//Note: |readStringStream|, |writeStringStream| and |OS.File.pump| | |
//do not exist yet |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment