Разархивировать с помощью adm-zip / unzipper / yauzl не удается в узле 10 молча - PullRequest
1 голос
/ 27 апреля 2020

Я пытался добавить сценарий использования в мой код, в котором я пытаюсь распаковать zip-файл, который слишком велик для размещения на диске, и я ожидаю, что мой код выдаст ENOSP C. Я перепробовал несколько библиотек, но ни одна из них не выдавала ошибку, скорее молча, без завершения архивирования Я ожидаю, что они выдадут ошибку ENOSP C, но все пакеты, похоже, регистрируют первый оператор info, в котором говорится, что разархивирование было начато, но ничего после этого. Большинство из них создают неполные папки, что бы они ни писали до того, как на диске не осталось места. Вот как мой код выглядит для каждой из библиотек.

Мой код с использованием adm-zip :

exports.unzip = function(source, destination) {
    console.info("Started un-zipping from source: %s to destination: %s", source, destination);
    try {
        const zip = new AdmZip(source);
        zip.extractAllTo(destination, true);
        console.info("done unzipping");
    } catch (error) {
        console.error("Unzipping failed. Reason: %s", error)
        throw new Error(error)
    }
};

Код с использованием yauzl :

exports.extractZip = function(source, destination) {
    return new Promise(function(resolve, reject) {
      console.log("Extracting zip: '" + source + "' to '" + destination + "'");

      yauzl.open(source, {
        lazyEntries: true
      }, function(err, zipfile) {
        if (err) throw err;
        zipfile.readEntry();
        zipfile.on("error", function (err) {
            console.error("Something went wrong while extracting!");
            reject(new Error(err));
        });
        zipfile.on("end", function () {
            console.log("Completed extracting zip!");
            resolve();
        });
        zipfile.on("entry", function(entry) {
          if (/\/$/.test(entry.fileName)) {
            // directory file names end with '/'
            mkdirp(destination + '/' + entry.fileName, function(err) {
              if (err) {
                  console.error("Something went wrong while extracting!");
                  throw err;
              }
              zipfile.readEntry();
            });
          } else {
            // file entry
            zipfile.openReadStream(entry, function(err, readStream) {
              if (err) {
                console.error("Something went wrong while extracting!");
                throw err;
              }
              // ensure parent directory exists
              mkdirp(destination + '/' + path.dirname(entry.fileName), function(err) {
                if (err) throw err;
                readStream.pipe(fs.createWriteStream(destination + '/' + entry.fileName));
                readStream.on("end", function() {
                  zipfile.readEntry();
                });
              });
            });
          }
        });
      });
    });
  }

Код с использованием Unzipper :

exports.unzip2 = function(source, destination) {
    console.info("Started un-zipping from source: %s to destination: %s", source, destination);
    try {
        fs.createReadStream(source)
        .pipe(unzipper.Extract({ path: destination }))
        .on('error',function (err){
            console.error("something went wrong", err.code);
            throw err;
        });
    } catch (error) {
        console.error("Unzipping failed. Reason: %s", error)
        throw new Error(error)
    }
};

Использование кода extract-zip :

exports.extractArchive = async function(source, destination) {
    try {
        extract(source, { dir: destination }, function (err) {
            if (err) {
                console.error("Something went wrong!", err.code);
                throw err;
            }
        });
        console.log('Extraction complete')
      } catch (err) {
        // handle any errors
      }
};

Что-то не так с моим кодом? Есть ли какое-то особое событие, которое мне нужно слушать?

1 Ответ

0 голосов
/ 28 апреля 2020

После некоторой ошибки и ошибок в Yauzl и unzipper, казалось, что unzipper сработал (выбрасывает ENOSP C, когда во время распаковки не хватает места на диске) со следующим кодом.

exports.unzip2 = function(source, destination) {
    return new Promise(function(resolve, reject) {
        console.info("Started un-zipping from source: %s to destination: %s", source, destination);
        try {
            var sourceStream = fs.createReadStream(source);
            sourceStream.on('error',function (err){
                console.error("something went wrong", err.code);
                reject(new Error(err));
            });
            var destinationStream = unzipper.Extract({ path: destination });
            destinationStream.on('error',function (err){
                console.error("something went wrong", err.code);
                reject(new Error(err));
            });
            destinationStream.on('close',function (){
                console.log("Completed extract!");
                resolve();
            });
            sourceStream.pipe(destinationStream).on('error',function (err){
                console.error("something went wrong", err.code);
                reject(new Error(err));
            });;
        } catch (error) {
            console.error("something went wrong", err.code);
            reject(new Error(err));
        }
    });
};
...