Skip to content

Commit

Permalink
Implement fs.readdirSync()
Browse files Browse the repository at this point in the history
  • Loading branch information
ry committed Feb 22, 2010
1 parent 49cd1bb commit 05ae932
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 19 deletions.
4 changes: 4 additions & 0 deletions doc/api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
25 changes: 22 additions & 3 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
Expand Down Expand Up @@ -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);
}
}

Expand Down
41 changes: 25 additions & 16 deletions test/mjsunit/test-readdir.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 05ae932

Please sign in to comment.