diff --git a/doc/api.txt b/doc/api.txt index f85e29e0b1..a69d73c029 100644 --- a/doc/api.txt +++ b/doc/api.txt @@ -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). diff --git a/src/node_file.cc b/src/node_file.cc index 07f8ab5cec..d1e257a26f 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -336,9 +337,27 @@ static Handle 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 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); } } diff --git a/test/mjsunit/test-readdir.js b/test/mjsunit/test-readdir.js index f740560a55..4ded485571 100644 --- a/test/mjsunit/test-readdir.js +++ b/test/mjsunit/test-readdir.js @@ -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);