Add writeFile() to /file.js

Initial patch by Tim Caswell.
pull/22966/head
Ryan Dahl 2009-09-22 12:15:45 +02:00
parent 07792afe0a
commit a02ca7a590
1 changed files with 29 additions and 0 deletions

View File

@ -12,6 +12,35 @@ function debugObject (obj) {
}
}
exports.writeFile = function (filename, data, encoding) {
var promise = new node.Promise();
encoding = encoding || "utf8"; // default to utf8
node.fs.open(filename, node.O_WRONLY | node.O_TRUNC | node.O_CREAT, 0666)
.addCallback(function (fd) {
function doWrite (_data) {
node.fs.write(fd, _data, 0, encoding)
.addErrback(function () {
node.fs.close(fd);
})
.addCallback(function (written) {
if (written == _data.length) {
node.fs.close(fd);
} else {
doWrite(_data.slice(written));
}
});
}
doWrite(data);
})
.addErrback(function () {
promise.emitError()
});
return promise;
};
exports.File = function (filename, mode, options) {
var self = this;