From: Ryan Dahl Date: Tue, 22 Sep 2009 10:15:45 +0000 (+0200) Subject: Add writeFile() to /file.js X-Git-Tag: v0.1.12~16 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=a02ca7a590a9cb9ad76fe557e54a960a0452e90b;p=platform%2Fupstream%2Fnodejs.git Add writeFile() to /file.js Initial patch by Tim Caswell. --- diff --git a/lib/file.js b/lib/file.js index f571ce9..e024d00 100644 --- a/lib/file.js +++ b/lib/file.js @@ -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;