acd4f13705acd54cc2f8bb99f2291c04af2f91d1
[platform/upstream/nodejs.git] / src / file.js
1 node.fs.exists = function (path, callback) {
2   var p = node.fs.stat(path);
3   p.addCallback(function () { callback(true); });
4   p.addErrback(function () { callback(false); });
5 };
6
7 node.fs.cat = function (path, encoding) {
8   var promise = new node.Promise();
9   
10   encoding = encoding || "utf8"; // default to utf8
11
12   node.fs.open(path, node.O_RDONLY, 0666).addCallback(function (fd) {
13     var content = "", pos = 0;
14
15     function readChunk () {
16       node.fs.read(fd, 16*1024, pos, encoding).addCallback(function (chunk, bytes_read) {
17         if (chunk) {
18           if (chunk.constructor === String) {
19             content += chunk;
20           } else {
21             content = content.concat(chunk);
22           }
23
24           pos += bytes_read;
25           readChunk();
26         } else {
27           promise.emitSuccess(content);
28           node.fs.close(fd);
29         }
30       }).addErrback(function () {
31         promise.emitError();
32       });
33     }
34     readChunk();
35   }).addErrback(function () {
36     promise.emitError(new Error("Could not open " + path));
37   });
38   return promise;
39 };