首页 > 解决方案 > 在电子中使用 jsftp 删除文件夹及其子文件夹

问题描述

我有一个电子项目,想使用 jsftp 删除 ftp 服务器中的文件夹及其子文件夹。我创建了一个类以使其更易于使用。

    const ftp = require('jsftp')

class Storage {
    constructor() {
        this.config = {
            host: '127.0.0.1',
            user: 'admin',
            pass: '',
            port: 21
        }

        this.nextPath = []
    }

    async makeDir(paths) {
        const path = paths.split('/')
        let nextPath = []
        
        path.forEach(async (folderName, i) => {
            nextPath.push(folderName)

            const nextFolder = nextPath.length > 1 ? nextPath.join('/') : folderName

            new Promise((resolve) => {
                new ftp(this.config).raw('mkd', nextFolder, (err, data) => {
                    if (err) return console.error(err);
                })

                return resolve()
            })
        })
    }

    async removeDir(path) {
        const removeCurrentFolder = async (dir) => {
            return await new Promise((resolve) => {
                new ftp(this.config).raw('rmd', `${dir}`, (err, data) => {
          console.log('folder removed');
          
                    if (err) {
                        return console.error(err); 
                    }

                resolve();
                })
            })
        }
    
        const checkIfEmptyFolder = async (dir) => {
      console.log(dir);
          await new Promise(async (resolve) => {
        await this.ls(dir).then(async (fileOrDirectory) => {

          if(fileOrDirectory.length) { // check if file or directory is not empty
            await Promise.all([...fileOrDirectory].map(async (el) => {
              let whichFolder;

              if(el.isFolder) {
                this.nextPath.push(el.name);
                whichFolder = this.nextPath.join('/')
                await checkIfEmptyFolder(whichFolder)
              } 

            }))
          } else {
            await removeCurrentFolder(this.nextPath.join('/')).then(() => { this.nextPath.pop();console.log('done removing'); })
            return this.nextPath.length ? await checkIfEmptyFolder(this.nextPath.join('/')) : console.log('done');
          }
        })

        resolve()
      })
        }

    this.nextPath.push(path)
      await checkIfEmptyFolder(path)
    }

    async ls(path) {
        let files = []

        return new Promise((resolve, reject) => {
            new ftp(this.config).ls(path || '.', (err, res) => {
                if(err) return reject(err)

                res.forEach(file => {
                    files.push({ name: file.name, isFolder: file.type === 1, size: parseInt(file.size) })
                })
                
                return resolve(files)
            })
        })
    }
}

module.exports = new Storage()

如果文件夹包含一个子文件夹,则此类有效。如果文件夹包含两个或更多子文件夹,则会显示此错误:Uncaught Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:209)

我在做什么这是错的?我错过了什么?

谢谢

标签: javascriptelectron

解决方案


推荐阅读