如何使用nodeJS列出所有子目录和文件? [英] How to list all subdirectories and files using nodeJS?

查看:99
本文介绍了如何使用nodeJS列出所有子目录和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


使用节点 ssh2-sftp-client,我想递归列出所有SSH 远程目录根目录(第二次是文件).

我正在使用 nodejs

node v12.15.0

我发现了一个有用的相同但没有回答的 StackOverflow问题.

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

const Client = require('ssh2-sftp-client');const sshConfig = {主机:process.env.REMOTE_SSH_HOST,端口:22,用户名:process.env.REMOTE_SSH_USERNAME,密码:process.env.REMOTE_SSH_PASSWORD,就绪超时:99999,};让 sftp = 新客户端();sftp.connect(sshConfig).then(() => {返回 sftp.list('/tmp');}).那么(数据=> {console.log(data, '数据信息');}).catch(err => {console.log(err, 'catch error');});

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

sftp.list(...).forEach 不是函数

尽管 sftp.list() 返回一个数组.
我知道 sftp.list 方法有一些东西会返回一个 Promise,然后是一个数组,但不知道我应该修改什么以及在哪里修改.

这是我的代码:
sshList.js

const Client = require('ssh2-sftp-client');const sshConfig = {主机:process.env.REMOTE_SSH_HOST,端口:22,用户名:process.env.REMOTE_SSH_USERNAME,密码:process.env.REMOTE_SSH_PASSWORD,就绪超时:99999,};让 sftp = 新客户端();//读取子目录的函数异步函数 SubRead(sub, parentDirectory) {if (sub['type'] === 'd') {等待读取(parentDirectory + '/' + sub['name']);}}异步函数读取(目录){console.log('Read(' + directory + ')');const 结果 = sftp.list(目录);result.forEach( x => SubRead(x, directory) );}异步函数主(目录){尝试 {console.log('正在连接...');等待 sftp.connect(sshConfig).then(async () => {console.log('已连接');等待读取(目录);});}赶上(e){console.error(e.message);} 最后 {console.log('关闭会话...');等待 sftp.end();console.log('会话关闭.');}}console.log('应用程序启动');main('/home/user/path').then(r => {console.log('应用程序结束.');});

启动

节点 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

运行节点命令(见上)给出了一个不完整的结果:

应用程序启动正在连接...连接的阅读(/home/iliad/alain)阅读(/home/iliad/alain/Level1_B)阅读(/home/iliad/alain/Level1_A)阅读(/home/iliad/alain/Level1_C)闭幕式...会议结束.申请结束.

无法找到Level 2"目录!
我在期待(不要考虑# Missing"文本):

应用程序启动正在连接...连接的阅读(/home/iliad/alain)阅读(/home/iliad/alain/Level1_B)阅读(/home/iliad/alain/Level1_B/Level2_BA)#缺失阅读(/home/iliad/alain/Level1_B/Level2_BB)#缺失阅读(/home/iliad/alain/Level1_B/Level2_BC)#缺失阅读(/home/iliad/alain/Level1_A)阅读(/home/iliad/alain/Level1_A/Level2_AA)#缺失阅读(/home/iliad/alain/Level1_A/Level2_AA/Level4_AAA)#缺失阅读(/home/iliad/alain/Level1_A/Level2_AB)#缺失阅读(/home/iliad/alain/Level1_A/Level2_AC)#缺失阅读(/home/iliad/alain/Level1_C)阅读(/home/iliad/alain/Level1_C/Level2_CA)阅读(/home/iliad/alain/Level1_C/Level2_CB)闭幕式...会议结束.申请结束.

我错过了什么?
欢迎任何帮助!

解决方案

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

const Client = require('ssh2-sftp-client');const sshConfig = {主机:process.env.REMOTE_SSH_HOST,端口:22,用户名:process.env.REMOTE_SSH_USERNAME,密码:process.env.REMOTE_SSH_PASSWORD,就绪超时:99999,};让 sftp = 新客户端();异步函数读取(目录){console.log('Read(' + directory + ')');const 结果 = 等待 sftp.list(目录);for(const sub of result) {if (sub['type'] === 'd') {等待读取(目录 + '/' + sub['name']);}}}异步函数主(目录){尝试 {console.log('正在连接...');等待 sftp.connect(sshConfig).then(() => {console.log('已连接');等待读取(目录);});}赶上(e){console.error(e.message);} 最后 {console.log('关闭会话...');等待 sftp.end();console.log('会话关闭.');}}console.log('应用程序启动');main('/home/user/path').then(r => {console.log('应用程序结束.');});


Using node ssh2-sftp-client, I'd like to recursively list all directories (and in a second time, files) of a SSH-remote directory root.

I'm using nodejs

node v12.15.0

I've found a usefulness same but non answered StackOverflow question.

Documentation "basic usage" (see ssh2-sftp-client) gives a standard use of sftp connection and list of directory '/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');
});

I've tried to add a function recursively reading every sub-directories, but I got an error on forEach sentence saying :

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

although sftp.list() returns an array.
I know there is something with sftp.list method that return a Promise and then an array, but cannot figure out what and where I should modify.

Here is my code :
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.');
});

Launch with

node sshList.js


Adding sample structure

Let say remote directory "/home/user/path" to read has this tree structure :

.
├── 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

Running node command (see upper) gives an incomplete result :

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.

No way to find "Level 2" directories !
I was expecting (do not consider "# Missing" text) :

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.

What am I missing ?
Any help will be welcome !

解决方案

sftp.list returns a promise so you need to await it before using it. Something like this should work

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.');
});

这篇关于如何使用nodeJS列出所有子目录和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆