javascript - 如何使用nodeJS列出所有子目录和文件?

标签 javascript node.js ssh


使用 Node ssh2-sftp-client ,我想递归地列出 SSH 远程目录根的所有目录(以及第二次的文件)。

我正在使用nodejs

node v12.15.0

我发现了一个有用的东西 same but non answered StackOverflow question .

文档“基本用法”(请参阅​​ ssh2-sftp-client )给出了 sftp 连接和目录“/tmp”列表的标准用法:

const Client = require('ssh2-sftp-client');
const sshConfig = {
    host: process.env.REMOTE_SSH_HOST,
    port: 22,
    username: process.env.REMOTE_SSH_USERNAME,
    password: process.env.REMOTE_SSH_PASSWORD,
    readyTimeout: 99999,
};
let sftp = new Client();
sftp.connect(sshConfig).then(() => {
    return sftp.list('/tmp');
}).then(data => {
    console.log(data, 'the data info');
}).catch(err => {
    console.log(err, 'catch error');
});

我尝试添加一个递归读取每个子目录的函数,但在 forEach 句子中出现错误:

sftp.list(...).forEach is not a function

虽然 sftp.list() 返回一个数组。
我知道 sftp.list 方法中有一些东西会返回一个 Promise,然后返回一个数组,但无法弄清楚我应该修改什么以及在哪里修改。

这是我的代码:
sshList.js

const Client = require('ssh2-sftp-client');
const sshConfig = {
    host: process.env.REMOTE_SSH_HOST,
    port: 22,
    username: process.env.REMOTE_SSH_USERNAME,
    password: process.env.REMOTE_SSH_PASSWORD,
    readyTimeout: 99999,
};
let sftp = new Client();

// Function to read sub-directories
async function SubRead(sub, parentDirectory) {
    if (sub['type'] === 'd') {
        await Read(parentDirectory + '/' + sub['name']);
    }
}
async function Read(directory) {
    console.log('Read(' + directory + ')');
    const result = sftp.list(directory);
    result.forEach( x => SubRead(x, directory) );
}
async function main(directory) {
    try {
        console.log('Connecting...');
        await sftp.connect(sshConfig).then(async () => {
            console.log('Connected');
            await Read(directory);
        });
    } catch (e) {
        console.error(e.message);
    } finally {
        console.log('Closing session...');
        await sftp.end();
        console.log('Session closed.');
    }
}
console.log('Application started');
main('/home/user/path').then(r => {
    console.log('Application ended.');
});

启动

node sshList.js
<小时/>

添加示例结构

假设要读取的远程目录“/home/user/path”具有以下树结构:

.
├── Level1_A
│   ├── Level2_AA
│   │   ├── Level3_AAA
│   │   ├── toto
│   │   ├── toto.txt
│   │   ├── txttoto
│   │   └── txt.toto
│   ├── Level2_AB
│   └── Level2_AC
├── Level1_B
│   ├── Level2_BA
│   ├── Level2_BB
│   └── Level2_BC
└── Level1_C
    ├── Level2_CA
    └── Level2_CB

运行 Node 命令(见上)给出不完整的结果:

Application started
Connecting...
Connected
Reading(/home/iliad/alain)
Reading(/home/iliad/alain/Level1_B)
Reading(/home/iliad/alain/Level1_A)
Reading(/home/iliad/alain/Level1_C)
Closing session...
Session closed.
Application ended.

无法找到“2 级”目录!
我期待着(不要考虑“# Missing”文本):

Application started
Connecting...
Connected
Reading(/home/iliad/alain)
Reading(/home/iliad/alain/Level1_B)
Reading(/home/iliad/alain/Level1_B/Level2_BA) # Missing
Reading(/home/iliad/alain/Level1_B/Level2_BB) # Missing
Reading(/home/iliad/alain/Level1_B/Level2_BC) # Missing
Reading(/home/iliad/alain/Level1_A)
Reading(/home/iliad/alain/Level1_A/Level2_AA) # Missing
Reading(/home/iliad/alain/Level1_A/Level2_AA/Level4_AAA) # Missing
Reading(/home/iliad/alain/Level1_A/Level2_AB) # Missing
Reading(/home/iliad/alain/Level1_A/Level2_AC) # Missing
Reading(/home/iliad/alain/Level1_C)
Reading(/home/iliad/alain/Level1_C/Level2_CA)
Reading(/home/iliad/alain/Level1_C/Level2_CB)
Closing session...
Session closed.
Application ended.

我缺少什么?
欢迎任何帮助!

最佳答案

sftp.list 返回一个 promise ,因此您需要在使用它之前等待它。像这样的东西应该可以工作

const Client = require('ssh2-sftp-client');
const sshConfig = {
    host: process.env.REMOTE_SSH_HOST,
    port: 22,
    username: process.env.REMOTE_SSH_USERNAME,
    password: process.env.REMOTE_SSH_PASSWORD,
    readyTimeout: 99999,
};
let sftp = new Client();

async function Read(directory) {
    console.log('Read(' + directory + ')');
    const result = await sftp.list(directory);
    for(const sub of result) {
      if (sub['type'] === 'd') {
          await Read(directory + '/ ' + sub['name']);
      }
    }
}

async function main(directory) {
    try {
        console.log('Connecting...');
        await sftp.connect(sshConfig).then(() => {
            console.log('Connected');
            await Read(directory);
        });
    } catch (e) {
        console.error(e.message);
    } finally {
        console.log('Closing session...');
        await sftp.end();
        console.log('Session closed.');
    }
}
console.log('Application started');
main('/home/user/path').then(r => {
    console.log('Application ended.');
});

关于javascript - 如何使用nodeJS列出所有子目录和文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60188732/

相关文章:

javascript - 访问 promise 回调中对象的 'this'(然后)

python - 如何解决 - 与 192.168.X.X 的连接已关闭?

linux - 如何使用 codecommit 设置 git,这样我就不必每次都添加 ssh key ID?

node.js - 通过node中的require访问全局安装的包

node.js - Bull 队列尚未完成

javascript - 使用 'opn' npm 模块在 Docker 中未处理的 promise 拒绝

linux - Linux 容器会休眠吗?

javascript - 当变量是函数参数时,应用程序抛出变量引用错误

javascript - 将鼠标悬停在所有列表项上,指定项除外

javascript - 语法错误 : Unexpected token when running selenium-javascript tests