【问题标题】:How to zip file before saving original on drive?如何在将原始文件保存到驱动器之前压缩文件?
【发布时间】:2016-09-07 15:03:20
【问题描述】:

在这段代码中我得到 p(file path) 并且可以下载它

function createCSV(){
  return mytmp.getTempDir((tmpPath) => {
    return new Promise(function (resolve, reject) {

      let p  = path.resolve(tmpPath, "snake_case_users33.csv");
      var ws = fs.createWriteStream(p);

      csv
        .write([
          {a: "a1", b: "b1"},
          {a: "a2", b: "b2"}
        ], {headers: true})
        .pipe(ws);

      resolve(p);

    });
  });
}

但我需要在格式化日期之前压缩 .csv 文件,或者首先格式化 .csv 文件,然后压缩并保存在驱动器上并获取路径。

一开始我需要创建 csv:

let p = path.resolve(tmpPath, "snake_case_users.csv");
        var output = fs.createWriteStream(p);
        csv.write([
            {a: "a1", b: "b1"},
            {a: "a2", b: "b2"}
          ], {headers: true});

//below let zipPath = path.resolve(tmpPath, "snake_case_users.zip"); and zip

也许在我们可以使用 zipPath 以某种方式压缩这个 csv 之后?

【问题讨论】:

  • 您的代码后面的句子有点令人困惑。你能试着改写一下吗?
  • @leigero,我想压缩格式的 csv 文件并获取下载路径

标签: javascript node.js zip export-to-csv fs


【解决方案1】:

我建议使用归档模块。

https://github.com/archiverjs/node-archiver

它非常易于使用,甚至可以将所有文件夹打包成zip。

这里是从文件夹中生成 zip 的示例代码

function archive (cb) {

  var archive = require('archiver');
  var timestamp = new Date().getTime().toString();
  // this self.logPath + '/archive' + timestamp + '.zip' is the path to zip file. 
  //You can use any path you like. 
  var zipPath = self.logPath + '/archive' + timestamp + '.zip'
  var output = fs.createWriteStream(zipPath);
  var archive = archiver('zip');

  output.on('close', function() {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');

    return cb("All ok or path to zip");
  });

  archive.on('error', function(err) {
    return cb("Error");
  });

  archive.pipe(output);
  //read directory
  var allLogs = fs.readdirSync('path to dir or to file');
  //append files to archive
  async.eachSeries(allLogs, function(fileName, callback){
      var file = path.join(self.logPath, fileName);
      archive.append(fs.createReadStream(file), { name: fileName });
      callback();
  }, function(){
      //finalize it will trigger on close event
      archive.finalize();
  });
}

当然你需要改变一些路径,但其他一切都应该没问题。

希望对你有帮助

【讨论】:

  • 我如何获得 zip 文件路径以使用我的压缩 csv 下载此文件?
  • 检查 var zipPath 变量
  • 我为您编辑了我的问题,请检查。我需要存档,其中包含 csv
  • 当您完成创建 csv...只需使用 pathToCSVFile 创建读取流,然后使用 archive.append(您读取流)并在流结束时解析。追加 API archiverjs.com/docs/Archiver.html#append
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2011-02-17
  • 2014-06-20
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多