node.js - 如何递归地遍历目录,通过 node.js 中的套接字发送所有文件名?

标签 node.js sockets asynchronous socket.io fs

我正在尝试使 Node 服务器能够通过网络套接字(递归地)将目录中找到的所有文件名发送到客户端。这里的想法是目录非常大,我想在读取整个目录之前开始在客户端获取结果。

我想这样的事情应该可以做到:

服务器端:

var express = require('express'),
  app = express(),
  server = require('http').createServer(app),
  io = require('socket.io').listen(server),
  fs = require('graceful-fs'),
  rootDirectory = "/some/absolute/path";
  port = 3000,
  recursivelyReadDirectory = function (rootDirectory) {
    // TODO
  },
  sync = io
    .of('/sync')
    .on('connection', function (socket) {
      recursivelyReadDirectory(rootDirectory).on('chunk', function (filename) {
       socket.emit('filename', filename);
      });
    });
server.listen(port);

客户端:

var socket = io.connect('http://localhost:3000/sync');
socket.on('filename', function (filename) {
  console.log(filename);
});

因此,如果我在服务器上的/some/absolue/path 中有以下内容:

.
|-- a
|   `-- c.txt
`-- b.txt

我希望客户端脚本能够记录

c.txt
b.txt

b.txt
c.txt

最佳答案

我创建了一个小型工作示例:

app.js

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    fs = require('fs'),
    rootDirectory = "c:/tmp",
    port = 3000,
    recursivelyReadDirectory = function (rootDirectory) {
        // TODO
    };

app.use(express.static(__dirname + '/public'));

var walk = function (dir, action, done) {

    // this flag will indicate if an error occured (in this case we don't want to go on walking the tree)
    var dead = false;

    // this flag will store the number of pending async operations
    var pending = 0;

    var fail = function (err) {
        if (!dead) {
            dead = true;
            done(err);
        }
    };

    var checkSuccess = function () {
        if (!dead && pending == 0) {
            done();
        }
    };

    var performAction = function (file, stat) {
        if (!dead) {
            try {
                action(file, stat);
            }
            catch (error) {
                fail(error);
            }
        }
    };

    // this function will recursively explore one directory in the context defined by the variables above
    var dive = function (dir) {
        pending++; // async operation starting after this line
        fs.readdir(dir, function (err, list) {
            if (!dead) { // if we are already dead, we don't do anything
                if (err) {
                    fail(err); // if an error occured, let's fail
                }
                else { // iterate over the files
                    list.forEach(function (file) {
                        if (!dead) { // if we are already dead, we don't do anything
                            var path = dir + "/" + file;
                            pending++; // async operation starting after this line
                            fs.stat(path, function (err, stat) {
                                if (!dead) { // if we are already dead, we don't do anything
                                    if (err) {
                                        fail(err); // if an error occured, let's fail
                                    }
                                    else {
                                        if (stat && stat.isDirectory()) {
                                            dive(path); // it's a directory, let's explore recursively
                                        }
                                        else {
                                            performAction(path, stat); // it's not a directory, just perform the action
                                        }
                                        pending--;
                                        checkSuccess(); // async operation complete
                                    }
                                }
                            });
                        }
                    });
                    pending--;
                    checkSuccess(); // async operation complete
                }
            }
        });
    };

    // start exploration
    dive(dir);
};

io
    .on('connection', function (socket) {
        walk(rootDirectory, function (path, stat) {
            console.log(path);
            socket.emit('filename', path);
        }, function (err) {
            if (err) {
                socket.emit('error', 'Something went wrong');
            } else {
                socket.emit('done');
            }
        });
    });
server.listen(port);

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost');
    socket.on('filename', function (data) {
        console.log(data);
    });
</script>
</body>
</html>

关于node.js - 如何递归地遍历目录,通过 node.js 中的套接字发送所有文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18909508/

相关文章:

javascript - MongoDB $regex 运算符不使用 mongoc 的 NodeJS

javascript - 为什么 async/await 函数运行两次?

TCP 发送不返回导致进程崩溃

php - PHP 中的异步请求

c# - 异步读写器储物柜

node.js - 使用 NPM 在专用 LAN 上安装 Node.js 模块?

node.js - 未找到传递参数的 Node 中的路径

python - 通常只允许每个套接字地址使用一次(但我需要使用相同的端口...)

用于收集仅包含主要实体的 IP 地址的所有主机名的 Python 脚本

javascript - 使用 JavaScript 和 ColdFusion 模板进行异步 DOM 操作?