Permalink
Browse files

Implement fs.readdirSync()

  • Loading branch information...
1 parent 49cd1bb commit 05ae932a0efa11678da9dfa3cf642c03859245f0 @ry ry committed Feb 22, 2010
Showing with 51 additions and 19 deletions.
  1. +4 −0 doc/api.txt
  2. +22 −3 src/node_file.cc
  3. +25 −16 test/mjsunit/test-readdir.js
View
@@ -635,6 +635,10 @@ Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments +(err, files)+ where +files+ is an array of
the names of the files in the directory excluding +"."+ and +".."+.
++fs.readdir(path, callback)+ ::
+Synchronous readdir(3). Returns an array of filenames excluding +"."+ and
++".."+.
+
+fs.close(fd, callback)+ ::
Asynchronous close(2).
View
@@ -3,6 +3,7 @@
#include <sys/types.h>
#include <sys/stat.h>
+#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
@@ -336,9 +337,27 @@ static Handle<Value> ReadDir(const Arguments& args) {
if (args[1]->IsFunction()) {
ASYNC_CALL(readdir, args[1], *path, 0 /*flags*/)
} else {
- // TODO
- return ThrowException(Exception::Error(
- String::New("synchronous readdir() not yet supported.")));
+ DIR *dir = opendir(*path);
+ if (!dir) return ThrowException(errno_exception(errno));
+
+ struct dirent *ent;
+
+ Local<Array> files = Array::New();
+ char *name;
+ int i = 0;
+
+ while (ent = readdir(dir)) {
+ name = ent->d_name;
+
+ if (name[0] != '.' || (name[1] && (name[1] != '.' || name[2]))) {
+ files->Set(Integer::New(i), String::New(name));
+ i++;
+ }
+ }
+
+ closedir(dir);
+
+ return scope.Close(files);
}
}
@@ -2,28 +2,37 @@ process.mixin(require("./common"));
var got_error = false;
-fs.readdir(fixturesDir, function (err, files) {
+var files = ['a.js'
+ , 'b'
+ , 'cycles'
+ , 'echo.js'
+ , 'multipart.js'
+ , 'nested-index'
+ , 'print-chars.js'
+ , 'test_ca.pem'
+ , 'test_cert.pem'
+ , 'test_key.pem'
+ , 'throws_error.js'
+ , 'x.txt'
+ ];
+
+
+puts('readdirSync ' + fixturesDir);
+var f = fs.readdirSync(fixturesDir);
+p(f);
+assert.deepEqual(files, f.sort());
+
+
+puts("readdir " + fixturesDir);
+fs.readdir(fixturesDir, function (err, f) {
if (err) {
puts("error");
got_error = true;
} else {
- p(files);
- assert.deepEqual(['a.js'
- , 'b'
- , 'cycles'
- , 'echo.js'
- , 'multipart.js'
- , 'nested-index'
- , 'print-chars.js'
- , 'test_ca.pem'
- , 'test_cert.pem'
- , 'test_key.pem'
- , 'throws_error.js'
- , 'x.txt'
- ], files.sort());
+ p(f);
+ assert.deepEqual(files, f.sort());
}
});
-puts("readdir " + fixturesDir);
process.addListener("exit", function () {
assert.equal(false, got_error);

0 comments on commit 05ae932

Please sign in to comment.