Add writeFile() to /file.js
authorRyan Dahl <ry@tinyclouds.org>
Tue, 22 Sep 2009 10:15:45 +0000 (12:15 +0200)
committerRyan Dahl <ry@tinyclouds.org>
Tue, 22 Sep 2009 10:15:49 +0000 (12:15 +0200)
Initial patch by Tim Caswell.

lib/file.js

index f571ce9..e024d00 100644 (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;