如何使用node.js列出目录IN ORDER的内容?

时间:2011-06-05 22:11:46

标签: javascript list node.js directory inorder

我是一位经验丰富的程序员,我刚刚发现了node.js.我喜欢JavaScript,因为那是我开始的地方(Web开发)所以能够用它编写服务器端代码真是太棒了。

目前,我正在进行一个简单的练习,一个WebSocket / HTTP服务器,当我遇到一个轻微的烦恼时,我开始添加一个目录列表功能:当我列出某个目录中的目录和文件时,它们就是没有任何顺序。我希望它们首先列出目录,然后按字母顺序列出文件(比如'ls'命令)。我有一种感觉,因为它的异步,但我并不完全正面。任何帮助将不胜感激。

BTW,这是我的代码:

var sys = require("sys");
var ws = require('websocket-server');
var fs = require("fs");
var path = require("path");
var url = require("url");

function log(data){
  sys.log("\033[0;32m"+data+"\033[0m");
}

var server = ws.createServer();
server.listen(3400);
log("Listening on 3400 for HTTP and WS");

server.addListener("request", function(request, response){
  log("HTTP: Connected: " + request.connection.remoteAddress);
  var uri = url.parse(request.url).pathname;
  var filename = path.join("/home/brandon", uri);
  log("HTTP: " + request.connection.remoteAddress + " Requested: " + filename);
  path.exists(filename, function(exists) {
        if(!exists) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\n");
            log("HTTP: " + filename + " Does Not Exist. 404 returned to " + request.connection.remoteAddress);
            response.end();
            log("HTTP: Disconnected: " + request.connection.remoteAddress);
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if(err) {
                if(err.errno === 21){
                    fs.readdir(filename, function(err1, files){
                        if(err1){ 
                            response.writeHead(500, {"Content-Type": "text/plain"});
                            response.write("Error when reading directory: " + err1 + "\n");
                            log("HTTP: " + filename + " Could Not Be Read. 500 returned to " + request.connection.remoteAddress);
                            response.end();
                            log("HTTP: Disconnected: " + request.connection.remoteAddress);
                            return;
                        } else {
                            response.writeHead(200);
                            response.write("<HTML><HEAD><title>Directory Listing for " + uri + "</title></HEAD><BODY><h1>Directory Listing for " + uri + "</h1>");
                            response.write("<ul>");
                            function printBr(element, index, array) {
                                response.write("<li>" + element + "</li>");
                            }
                            /*for( i in files ){
                                response.write("<li>" + files[i] + "</li>");
                            }*/
                            files.forEach(printBr);
                            response.write("</ul>");
                            response.write("</BODY></HTML>");
                            log("HTTP: Directory listing for " + filename + " sent to " + request.connection.remoteAddress);
                            response.end();
                            log("HTTP: Disconnected: " + request.connection.remoteAddress);
                            return;
                        }
                    });
                    return;
                }
                response.writeHead(500, {"Content-Type": "text/plain"});
                response.write("Error when reading file: " + err + "\n");
                log("HTTP: " + filename + " Could Not Be Read. 500 returned to " + request.connection.remoteAddress);
                response.end();
                log("HTTP: Disconnected: " + request.connection.remoteAddress);
                return;
            }

            response.writeHead(200);
            response.write(file, "binary");
            log("HTTP: " + filename + " Read and Sent to " + request.connection.remoteAddress);
            response.end();
            log("HTTP: Disconnected: " + request.connection.remoteAddress);
        });
    });
});

server.addListener("connection", function(conn){
  log(conn.id + ": new connection");
  server.broadcast("New Connection: "+conn.id);
  conn.addListener("readyStateChange", function(readyState){
    log("stateChanged: "+readyState);
  });

  conn.addListener("close", function(){
    var c = this;
    log(c.id + ": Connection Closed");
    server.broadcast("Connection Closed: "+c.id);
  });

  conn.addListener("message", function(message){
    log(conn.id + ": "+JSON.stringify(message));

    server.broadcast(conn.id + ": "+message);
  });
});

这是浏览器中的输出: Output in Browser

**解决:**

感谢@Samir,我发现了如何做我想做的事情。我遍历目录内容的数组,检查项目是否是目录或文件,将它们分成两个数组(dirs的'dirs_in'和文件的'files_in'),按字母顺序排列两个数组,最后写出来

代码(第42-70行):

response.writeHead(200);
response.write("<HTML><HEAD><title>Directory Listing for " + uri + "</title></HEAD><BODY><h1>Directory Listing for " + uri + "</h1>");
response.write("<ul>");
function printBr(element, index, array) {
    response.write("<li>" + element);
    if( fs.statSync( path.join(filename + element) ).isDirectory() ){
        response.write(" is a <b>dir</b>");
    } else {
        response.write(" is a <b>file</b>");
    }
    response.write("</li>");
}
var dirs_in = [];
var files_in = [];
function sep(element, index, array) {
    if( fs.statSync( path.join(filename + element) ).isDirectory() ){
        dirs_in.push(element);
    } else {
        files_in.push(element);
    }
}
files.forEach(sep);
dirs_in.sort().forEach(printBr);
files_in.sort().forEach(printBr);
response.write("</ul>");
response.write("</BODY></HTML>");
log("HTTP: Directory listing for " + filename + " sent to " + request.connection.remoteAddress);
response.end();
log("HTTP: Disconnected: " + request.connection.remoteAddress);

浏览器输出: Problem Solved 附:我将删除'是一个dir'和'是一个文件'。他们只是为了测试。

1 个答案:

答案 0 :(得分:12)

如果您希望按名称排序,则可以先在阵列上调用sort()

files.sort().forEach(printBr);

例如,如果您想首先对目录进行排序,那么您需要获取更多信息。一个简单的实现是查询排序比较函数中每个文件的统计信息:

files.sort(function(a, b) {
    var aIsDir = fs.statSync(dir + "/" + a).isDirectory(),
        bIsDir = fs.statSync(dir + "/" + b).isDirectory();

    if (aIsDir && !bIsDir) {
        return -1;
    }

    if (!aIsDir && bIsDir) {
        return 1;
    }

    return a.localCompare(b);
}).forEach(printBr);

localCompare方法默认使用sort方法作为比较函数,因此如果它们都是“相等”条件,我们就委托给它。您可以根据需要进行扩展。我还建议您将isDirectory的结果至少存储在地图或其他内容中。此外,statSync适用于演示目的,但不适用于生产代码。请改用stat。这确实会导致稍微复杂的代码,但异步行为的好处是值得的。